请考虑下面的代码,了解正在发生的事情:
<?php // bar.php
$one = 1;
$two = 2;
和
<?php // foo.php
$someVar = 'var';
function foo()
{
$someOtherVar = 'otherVar';
include 'bar.php';
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
}
foo();
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
将输出类似
Array
(
[0] => someOtherVar
[1] => one
[2] => two
)
Array
(
[0] => GLOBALS
[1] => _ENV
[2] => HTTP_ENV_VARS
[3] => argv
[4] => argc
[5] => _POST
[6] => HTTP_POST_VARS
[7] => _GET
[8] => HTTP_GET_VARS
[9] => _COOKIE
[10] => HTTP_COOKIE_VARS
[11] => _SERVER
[12] => HTTP_SERVER_VARS
[13] => _FILES
[14] => HTTP_POST_FILES
[15] => _REQUEST
[16] => someVar
)
正如你可以看到,在函数内部foo()的作用域,你可以访问bar.php中包含的变量,但是一旦该函数被执行和控制ol流回到全球范围,例如,在调用foo()之后,变量不可用,因为它们没有被导出到函数范围之外。如果您在功能范围外包含bar.php,例如
include 'bar.php'; // instead of foo()
print_r(array_keys(get_defined_vars()));
你会得到
Array
(
...
[16] => someVar
[17] => one
[18] => two
)
放置了很多变数为全球范围内承担污染全局范围和冒着变量名称冲突的危险。也就是说,一个包含文件可能有一个$ row变量,另一个可能也有一个变量,它们会相互覆盖。将属于一起的东西封装到类/对象中和/或用全局范围替换为Registry pattern更好。
虽然我非常喜欢面向对象的方法,但您仍然可以在适当的位置使用它。只需从函数调用中返回所需的变量即可。
function foo()
{
$someOtherVar = 'otherVar';
include 'bar.php';
// this is why I do not like this approach $one pops out all of a sudden.
// I can deduct, it has to be in bar.php, but if you do that often, your
// code will be very hard to read.
return $one;
}
$user = foo(); // will contain $one then
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
// gives
Array
(
...
[16] => someVar
[17] => user
)
当然,如果你想拥有在呼叫期间宣布到foo(所有变量),你就必须把它们放在一个数组,因为只有一个值可以在同一时间内返回。但是,这基本上是当你注意到它变得笨拙,切换到类感觉很自然(至少对我来说)。
标题是“PHP包含错误”。你问你为什么会收到关于包含文件的错误,或者包含文件? – kiamlaluno 2009-12-19 10:25:20