从include返回值时的奇怪行为

问题描述

| 我在从include返回数组时遇到了一个奇怪的问题。手册中的示例显示了我所期望的行为: return.PHP
<?PHP
$var = \'PHP\';
return $var;
?>
noreturn.PHP
<?PHP
$var = \'PHP\';
?>
testreturns.PHP
<?PHP
$foo = include \'return.PHP\';
 // This is the expected behavior.
echo $foo; // prints \'PHP\'


$bar = include \'noreturn.PHP\';
echo $bar; // prints 1
?>
我的用法scnario给出了不同的结果。我通过使用简单的include调用Zend_Config来加载Zend_Config,它返回一个array(): config.PHP
<?PHP
/*
 *      Configuration options loaded in Zend_Config
 */ 
 return array(

 \'localDB\' => array(\'serverName\' => \'TESTDB\',\'uid\'        => \'TESTUSER\',\'pwd\'        => \'TESTPW\',\'DB\'         => \'TESTDB\'          
                 ),);

// in the app I can call Zend_config somewhat like this ...
$configfile = \'config.PHP\';

// zend_config takes an array as parameter,returned by the included file...
$config = Zend_config(include $config);
一切皆好。除了现在,我想覆盖此阵列以进行测试配置,而不更改文件,所以我这样做: testConfig.PHP
 $testsettings = include_once \'config.PHP\';

 // override the array
 $testsettings[\'localDB\'][\'serverName\'] = \"TEST\";

 //return the overriden array
 return $testsettings;
现在,奇怪的部分。当我执行PHP -f testConfig.PHP和var_dump()$ testsettings时,一切正常。 但是,如果我将此文件包含在测试用例中以具有orverriden设置值,则结果始终为(布尔值)true,如顶部所示的示例include,未设置返回值。 我已经想到了一些解决方法,但是出于好奇,我想知道是否有人对它为什么这样做有所了解。     

解决方法

        
include_once
在第一个之后每次返回
true
。所以线
$testsettings = include_once \'config.php\';
如果您在较早的代码中的任何地方都包含了
config.php
,则将
$testsettings
设置为true。     ,        也许不是布尔值,而是数组的数量。     ,        它在文档中。请查看有关处理退货的部分-http://us2.php.net/manual/zh/function.include.php。但基本上-不要这样做。