PHP包括范围类

时间:2012-06-28 19:35:36

标签: php class include scope

所以我有这个问题我有3个文件,如

2.PHP

<?php
$variable = 4;
?>

1.PHP

<?php
class foo {
function bar() {include_once('2.php');}
}
?>

的index.php

<?php
include_once('1.php');
$foo = new foo;
foo->bar();
echo $variable;
?>

为什么它告诉我变量没有价值? 如果我喜欢这个

<?php
include_once('1.php');
$foo = new foo;
foo->bar();
include_once('2.php');
echo $variable;
?>

它也不起作用。 只有这样

<?php
include_once('1.php');
$foo = new foo;
//foo->bar();
include_once('2.php');
echo $variable;
?>

它会起作用,任何解释? 感谢

2 个答案:

答案 0 :(得分:0)

$variable的范围仅在bar()函数

范围内

请参阅:http://php.net/manual/en/language.variables.scope.php

答案 1 :(得分:0)

您感到困惑includeinclude_once

当你使用后者时,文件加载和变量声明只会发生一次。如果您在方法范围内执行此操作,则不会在全局范围内第二次声明它。反之亦然。