加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

匿名函数 – 声明全局变量和在php中使用之间的区别是什么?

发布时间:2020-12-13 21:54:44 所属栏目: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,fu
在学习 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全局化?

$test2 = array("hello",$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","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,则只能使用一个范围向下访问它.在下一个示例中,$useRandom再次为null,因为它定义了两个范围“更高”,而use关键字仅在当前范围之外直接从范围导入变量.

$useRandom = "random";

function test()
{
    $test = array( "hello","what's up" );

    $result = usort( $test,$b ) use ( $useRandom ) {

            // isset( $useRandom ) == false

            if( $useRandom == "random" ) {
                return rand( 0,2 ) - 1;
            }
            else {
                return strlen( $a ) - strlen( $b );
            }
        }
    );
}

test();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读