PHP:关联数组中的匿名函数能否访问数组的其他成员?
在下面的示例中,是否可以从匿名函数中访问“str”值PHP:关联数组中的匿名函数能否访问数组的其他成员?,php,associative-array,Php,Associative Array,在下面的示例中,是否可以从匿名函数中访问“str”值 $foo = array( 'str' => 'THIS IS A STRING', 'fn' => function () { // is it possible from within here to access 'str'? } ); 如果在全局命名空间中定义了$foo,您应该能够通过$GLOBALS['foo']['str']访问它(或者通过全局$foo;构造使其可用)。如果不是(局部变量、参数、成
$foo = array(
'str' => 'THIS IS A STRING',
'fn' => function () {
// is it possible from within here to access 'str'?
}
);
如果在全局命名空间中定义了
$foo
,您应该能够通过$GLOBALS['foo']['str']
访问它(或者通过全局$foo;
构造使其可用)。如果不是(局部变量、参数、成员变量等),则必须将其(作为引用!)传递给匿名函数:
$foo = array(
'str' => 'THIS IS A STRING',
'fn' => function () use(&$foo) {
echo $foo['str'];
}
);
我发现了一种不使用全局变量的不同方法:
<?php
$arr = array("a" => 12,
"b" => function($num)
{
$c = $num * 2;
return $c;
});
echo $arr["b"]($arr["a"]);
?>
如果不包括方法括号,它将不起作用。谢谢!我可以通过
$GLOBALS['foo']['str']
访问它。请注意,如果它是本地变量或成员变量,您不能通过$GLOBAL
数组访问它。您不能直接访问$foo['str']
?(我现在没有一个支持闭包的PHP版本可供测试)不,$foo
未定义…可以直接访问$foo['str']
,请参阅下面的解决方案:
$arr["b"]();