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

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

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

Anonymous functions can use the variables defined in their enclosing scope using the use syntax.

例如:

    $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);
                            } 
                    );

为什么我不能让 $useRandom 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,因为它定义了两个范围 "higher" 并且 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();

在此示例中,您可能希望一旦将变量设置为全局变量,它就可用于后续函数。 运行 此代码的结果表明 不是 情况:

Am I a global? Yes, I am.

Global not available.

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

Using Globals 上查看这个答案,看看为什么这是个坏主意。