在包含的文件中声明的方法的PHP作用域

时间:2019-03-16 18:35:18

标签: php methods scope include

有人可以解释文件如何包含在方法中。 这是我不明白的: 假设我们有2个文件:

//a_variable.php
$variable=1;

//b_variable.php
$variable++;

从以下位置调用call_variable():

class TestView
{
    public static function a_variable()
    {
        require 'View/test/a_variable.php';
    }

    public static function b_variable()
    {
        require 'View/test/b_variable.php';
    }

    public static function call_variable()
    {
        self::a_variable();
        self::b_variable(); //doesn't know $variable. As expected.
    }
}

我得到了“未定义的变量:变量”,这是预料之中的,因为$ variable在a_variable()方法内部仅具有局部作用域。

但是,使用方法完全相同的代码:

//a_method.php
function method()
{
    echo "a";
}

//b_method.php
function method()
{
    echo "b";
}

从以下位置调用call_method():

class TestView
{
    public static function a_method()
    {
        require 'View/test/a_method.php';
    }

    public static function b_method()
    {
        require 'View/test/b_method.php';
    }

    public static function call_method()
    {
        self::a_method();
        self::b_method(); //DOES know method(). Why?
    }
}

我收到“致命错误:无法在第5行的View \ test \ b_method.php中重新声明method()(以前在View \ test \ a_method.php:4中声明)”

为什么所包含的方法的名称在调用方方法的范围之外可见?

0 个答案:

没有答案