PHP:关闭设置变量

问题描述 投票:0回答:2

在PHP中,闭包非常有用。但我可以使用闭包来设置数组元素吗?

$configs = [
    "y" => "1",
    "x" => function() { return "xxx"; },
];
echo $configs["y"];
echo $configs["x"];  // error

Recoverable fatal error: Object of class Closure could not
be converted to string on line 6 (last line)

有没有机会抛出闭包或闭包适用于数组初始化的任何东西?

在MacOSX上使用PHP 7.1.4

php closures
2个回答
1
投票

你想要一个IIFE(立即调用函数表达式):

$configs = [
  'y' => '1',
  'x' => (function () { return 'xxx'; })()
];

echo $configs['x'];

但是:Kua zxsw指出


0
投票

我将该功能定义为:

https://3v4l.org/O0fEm

然后将结果分配给变量:

function test(){   
    echo "Hello";
}
© www.soinside.com 2019 - 2024. All rights reserved.