我需要使用变量来在
array_map()
的回调内部定义 lambda 函数。对于我引用的变量,我收到“未定义的变量”警告。随后,我没有得到预期的结果。预期结果和实际结果在下面的代码中进行了注释。还给出了该问题的 PHP 沙箱。
$a = "hello";
$$a = "world";
# Prints "world" as expected.
echo $hello;
# GIVES WARNING !!!! (Undefined variable $hello)
$res = array_map(fn($number) => $number . $$a, ["1", "2"]);
# Expected: ["1 world", "2 world"]
# Actual: ["1", "2"]
echo var_dump($res);
尝试过:
您的问题是由于范围规则造成的。
$$a
不在函数的本地作用域中,而 $world
是您在与 array_map 函数相同的作用域中定义的常规变量,因此它可以被识别并可以在函数内部使用。
$a = "hello";
$$a = "world";
$world = $$a;
$res = array_map(fn($number) => $number . $world, ["1", "2"]);
var_dump($res);
变量 $$ 的行为方式与箭头函数内的常规 PHP 代码中的行为方式不同。 这里是带有解释和示例的文档;这就是为什么您收到“未定义变量”警告的原因。您可以使用常规匿名函数,它可以访问变量$$,而不是箭头函数
$a = "hello";
$$a = "world";
// Assigning the variables $$ to a new variable for use in the closure
$world = ${$a};
$res = array_map(function($number) use ($a, $world) {
return $number . $world;
}, ["1", "2"]);
var_dump($res);
关键字use
将变量$a带入匿名函数的作用域,以便可以在函数内部使用