脚本宝典收集整理的这篇文章主要介绍了匿名函数 – 声明全局变量和在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); } );
为什么我不能像以下一样将$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();
以上是脚本宝典为你收集整理的匿名函数 – 声明全局变量和在php中使用之间的区别是什么?全部内容,希望文章能够帮你解决匿名函数 – 声明全局变量和在php中使用之间的区别是什么?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。