我可以将一些php代码拆分为两个非功能部分(创建文件),然后以某种方式将它们包括在内,使它们像初始文件一样工作吗?可能不太清楚我想做什么,所以这里有一个例子:我得到了一个page.php,其中包含php和html代码。类似于:
<html>
<head>
</head>
<body>
some html code....
<?php if (condition) { ?>
some html code...
<?php } else { // some php redirect code or something similar } ?>
</body>
</html>
我可以在两个php文件中转换php代码并将其包含在内,以便在多个文件中使用它们吗?类似condition.php和end_condition.php,并将它们与include"…"一起使用;或要求"…";。
您可以将代码的任何部分放入外部文件和include
/require
中但是,每个单独的文件都需要完整且语法正确。不能在在中间拆分if..else
语句。因此,这个不起作用:
file1.php
<?php
if ($foo) {
...
include 'file2.php`;
file2.php
<?php
} else {
...
}
然而,这将工作得很好:
<?php
if ($foo) {
include 'foo.php';
} else {
include 'bar.php';
}
include
的工作方式与复制粘贴不同。每个PHP文件都需要是可执行的。
类似的东西。。。如果需要导入文件,可以使用require然后include
if(condition){
include 'end_condition.php';
}else{
include 'condition.php';
}
或者在一行中(尽管我从未尝试过,但只要尝试一下。)
condition ? include 'end_condition.php' : include 'condition.php';
使用require_once()包含其他php源文件:
<html>
<head>
</head>
<body>
some html code....
<?php if (condition) { require_once('file1.php'); }
else { require_once('file2.php'); } ?>
</body>
</html>
file1.php:
<?php echo 'condition is true'; ?>
file2.php:
<?php echo 'condition is false'; ?>