如何解决从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。但基本上-不要这样做。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。