匿名函数——声明全局变量和在php中使用有什么区别?


Anonymous functions - what's the difference between declaring a global variable and use in php?

在学习PHP中的匿名函数时,我遇到了这个:

匿名函数可以使用在其封闭函数中定义的变量

例如:

    $test = array("hello", "there", "what's up");
    $useRandom = "random";
    $result = usort($test, function($a, $b) use ($useRandom){
                                if($useRandom=="random")
                                    return rand(0,2) - 1;
                                else
                                    return strlen($a) - strlen($b);
                            } 
                    );

为什么我不能像下面那样让$ userrandom global呢?

    $test2 = array("hello", "there", "what's up");
    $useRandom = "random";
    $result = usort($test, function($a, $b){
                                global $useRandom;
                                if($useRandom=="random")
                                    return rand(0,2) - 1;
                                else
                                    return strlen($a) - strlen($b);
                            } 
                    );

这两种方法的区别是什么?

你的例子有点简化了。要获得区别,请尝试将示例代码包装到另一个函数中,从而在内部回调周围创建额外的作用域,该作用域不是全局的。

在下面的例子中,$useRandom在排序回调中总是null,因为没有全局变量$useRandom。您将需要使用use从非全局作用域的外部作用域访问变量。

function test()
{
    $test = array( "hello", "there", "what's up" );
    $useRandom = "random";
    $result = usort( $test, function ( $a, $b ) {
            global $useRandom;
            // isset( $useRandom ) == false
            if( $useRandom == "random" ) {
                return rand( 0, 2 ) - 1;
            }
            else {
                return strlen( $a ) - strlen( $b );
            }
        }
    );
}
test();

另一方面,如果有一个全局变量$useRandom,那么使用use只能向下一个作用域访问它。在下一个例子中,$useRandom还是null,因为它被定义了两个"更高"的作用域,而且use关键字只从当前作用域外直接导入变量。

$useRandom = "random";
function test()
{
    $test = array( "hello", "there", "what's up" );
    $result = usort( $test, function ( $a, $b ) use ( $useRandom ) {
            // isset( $useRandom ) == false
            if( $useRandom == "random" ) {
                return rand( 0, 2 ) - 1;
            }
            else {
                return strlen( $a ) - strlen( $b );
            }
        }
    );
}
test();

必须小心全局变量,原因有很多,其中最重要的是意外行为:

$foo = 'Am I a global?';
function testGlobal(){
    global $foo;
    echo $foo . ' Yes, I am.<br />';
}
function testAgain() {
    if(isset($foo)) {
        echo $foo . ' Yes, I am still global';
    } else {
        echo 'Global not available.<br />';
    }
}
testGlobal();
testAgain();

在本例中,您可能期望一旦将变量设置为全局变量,它将对后续函数可用。运行这段代码的结果表明,这个不是的情况:

我是全局的吗?是的,我是。

全局不可用。

以这种方式声明全局变量使变量在其全局声明的范围内可用(在本例中是函数testGlobal()),但不在脚本的一般范围内可用。