gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:19:43 27 4
gpt4 key购买 nike

在学习 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,因为它被定义为“更高”的两个作用域,而 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();

关于php - 匿名函数 - 声明全局变量和在 php 中使用有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740036/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com