PHP / Zend 抱怨未定义的变量
情况:
index.php:
<?php
include("foo.php");
include("baz.php");
foo("bar.php");
?>
baz.php:
<?php
$x = 42;
?>
foo.php:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
?>
bar.php:
<?php
echo $x;
?>
Zend 通知: 未定义变量: x
放置全局$x; bar.php 中删除了该通知,但我明白为什么首先会有一个关于此的通知。不包含很多工作,例如包含 C 标头? 这意味着解释后的代码将如下所示:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
$x = 42;
// this however, is included by a function...
// does the function's scope influence the stuff it includes?
echo $x; // undefined variable
?>
我的编辑器是 Eclipse/Zend 包。
The situation:
index.php:
<?php
include("foo.php");
include("baz.php");
foo("bar.php");
?>
baz.php:
<?php
$x = 42;
?>
foo.php:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
?>
bar.php:
<?php
echo $x;
?>
Zend notice: Undefined variable: x
Placing global $x; in bar.php removes the notice, but I understand why there is a notice about this in the first place.. Doesn't include pretty much work like including C headers? It would mean that the interpreted code would look like this:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
$x = 42;
// this however, is included by a function...
// does the function's scope influence the stuff it includes?
echo $x; // undefined variable
?>
My editor is the Eclipse/Zend package.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不是专家,所以如果我错了,请不要责怪我,但我认为 include_once 或 require_once 调用的文件是在调用者的上下文中调用的。 由于函数 foo() 不知道 $x,因此它调用的任何包含项也不会知道。 您可以通过使用与上面相同的设置在函数 foo() 内“声明” $x 进行实验。
I'm no expert, so please don't flame me if I'm wrong, but I think the file called by include_once or require_once is called in the context of the caller. Since function foo() won't know about $x then neither will any of its called includes. You could experiment by 'declaring' $x inside function foo() with the same setup as above.
我收到了很多这样的通知,因为我几乎总是使用“$o .= 'foo'”而没有任何定义。 我只是用 error_reporting(E_ALL ^ E_NOTICE) 隐藏它们,但我不知道在这种情况下这是否是最佳方式。
I get a bunch of those notices since I'm almost allways goes with "$o .= 'foo'" without any definition. I'm just hiding them with error_reporting(E_ALL ^ E_NOTICE), but I don't know if it's the optimal way in this case.
即使变量和函数位于同一文件中,它也不起作用。
不打印任何内容。
但是添加一个全局
,你可以看到“3”。
在函数中,除非声明全局变量,否则您看不到全局变量。
It doesn't work even if the variable and the function are in the same file.
Prints nothing.
But add a global
and you can see "3".
In a function you can't see global variables unless you declare it.
是的,它是导致问题的函数作用域,
如果您替换
为,
您会发现一切正常,因为它将它放入当前作用域而不是函数作用域
yes its the function scope that is causing your issues
if you replace
with
you'll see that everything works fine because it puts it into the current scope and not functions scope