从外部函数(PHP)访问函数中的局部变量


Access local variable in function from outside function (PHP)

有没有办法在PHP中实现以下功能,或者根本不允许这样做?(见下面的评论行)

function outside() {
    $variable = 'some value';
    inside();
}
function inside() {
    // is it possible to access $variable here without passing it as an argument?
}

请注意,使用全局关键字是不可取的,因为您无法控制(您永远不知道该变量在应用程序中的其他位置被使用和更改)。但是如果你使用类,它会让事情变得容易得多!

class myClass {
    var $myVar = 'some value';
    function inside() {
        $this->myVar = 'anothervalue';
        $this->outside(); // echoes 'anothervalue'
    }
    function outside() {
        echo $this->myVar; // anothervalue
    }
}

这是不可能的。如果$variable是全局变量,您可以通过global关键字访问它。但这是一种功能。所以你不能访问它。

不过,它可以通过$GLOBALS数组设置全局变量来实现。但同样,你在利用全球环境。

function outside() {
    $GLOBALS['variable'] = 'some value';
    inside();
}
function inside() {
        global $variable;
        echo $variable;
}

否,如果不将其作为参数传递,则无法从另一个函数访问函数的局部变量。

您可以为此使用global变量,但该变量不会保持为本地变量。

这是不可能的。您可以使用global来完成此操作。如果你只是不想定义参数,但可以在你可以使用的函数中给出它:

function outside() {
    $variable = 'some value';
    inside(1,2,3);
}
function inside() {
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />'n";
    }
}

请参阅php手册funct_get_args()

您无法访问函数中的局部变量。变量必须设置为全局

function outside() {
global $variable;
    $variable = 'some value';
    inside();
}
function inside() {
global $variable;
    echo $variable; 
}

这适用于