php3.0中通常会报告错误。以下举例说明: 假设被包含的文件为test.inc和主文件main.php位于一个目录中。test.inc的内容如下: test.inc <?php echo "Before the return<br>\n"; if(1) { return 27; } echo "After the return<br>\n"; ?>
假设在main.php文件中包含下面的语句: <?php $retval=include('test.inc'); echo "File returned:'$retval'<br>\n"; ?> php3.0解释器会在第二行报告错误,而不能得到include()语句的返回值。但在php4.0中会得到下面的结果: Before the return File returned: '27' 下边假设main.php改为: <?php include('test.inc'); echo "Back in main.html<br>\n"; ?> 在php4.0中的输出结果是: Before the return Back in main.html
在php5.0中的输出结果也是: Before the return Back in main.html
在php3.0中的输出结果是: Before the return 27Back in main.html
Parse error:parse error in /apache/htdocs/phptest/main.html on line 5
出现上面的错误是因为return语句位于{}内部而且不是一个函数内部。如果把{}去掉,使它位于test.inc的最外层,输出结果是: Before the return 27Back in main.html 之所以出现27,是因为在php3.0中不支持include()返回。
3.require_once()和include_once()语句 require_once()和include_once()语句分别对应于require()和include()语句。require_once()和include_once()语句主要用于需要包含多个文件时,可以有效地避免把同一段代码包含进去而出现函数或变量重复定义的错误。例如:如果创建两个文件util.inc和fool.inc,程序代码分别为: util.inc: <?php define(PHPVERSION,floor(phpversion())); echo "GLOBALS ARE NICE<br>\n"; function goodTea() { return "Olong tea tasts good!"; } ?> 和fool.inc: <?php require ("util.inc"); function showVar($var) { if(PHPVERSION==4) { print_r($var); } else { var_dump($var); } } ?> 然后在error_require.php中包含这两个文件: <?php require("fool.inc"); require("util.inc");//此句会产生一个错误 $foo=array("1",array("complex","quaternion")); echo "this is requiring util.inc again which is also<br>\n"; echo "required in fool.inc\n"; echo "Running goodTea:".goodTea()."<br>\n"; echo "Printing foo:<br>\n"; showVar($foo); ?> 当运行error_require.php时,输出结果如下: GLOBALS ARE NICE GLOBALS ARE NICE
Fatal error:Cannot redeclare goodTea() in util.inc on line 4
如果使用require_once()语句来代替 require()语句,就不会出现上面的错误。我们把error_require.php和fool.inc中的require()语句改为require_once()语句并重命名为error_require_once.php,这是显示结果如下: GLOBALS ARE NICE this is requiring util.inc again which is also required in fool.inc Running goodTea:Olong tea tastes good! Printing foo: Array([0] => 1 [1] => Array ([0] => complex [1] = quaternion))