Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在PHP的数组中放置匿名函数吗?_Php_Anonymous Function - Fatal编程技术网

我可以在PHP的数组中放置匿名函数吗?

我可以在PHP的数组中放置匿名函数吗?,php,anonymous-function,Php,Anonymous Function,可能重复: 我要走了 解析错误:语法错误,第87行的/home/codemonkey/dev/broadnet/bito.api2/broadnet/resources/broadmaprource.php中出现意外的T_函数 根据该代码: private $debugFunctions = array( "testing" => function() // Line 87 { return "I'm a test function!"; },

可能重复:

我要走了

解析错误:语法错误,第87行的/home/codemonkey/dev/broadnet/bito.api2/broadnet/resources/broadmaprource.php中出现意外的T_函数

根据该代码:

private $debugFunctions = array(
    "testing" => function() // Line 87
    {
        return "I'm a test function!";
    },
    "foo" => function()
    {
        return "bar";
    }
);
我觉得我可以在任何可以使用
$variables
的地方使用匿名PHP函数。这是个例外,还是我做错了什么


我使用的是PHP5.3.9

您不能使用class属性,属性初始化必须是一个常量值

初始化必须是一个常量值——也就是说,它必须能够 在编译时进行计算,并且不能依赖于运行时 信息,以便进行评估


不是那样的,看看吧。 它在当前作用域中创建一个新函数并返回函数名

private $debugFunctions = array(
    "testing" => create_function('', 'return "I\'m a test function!";'),
    "foo" => create_function('', 'return "bar";');
);
不过,不确定上述示例是否有效。我没有时间测试它

还请注意,使用create_函数会显著降低应用程序的速度,具体取决于您使用它的频率。

使用构造函数:

class TestClass {
    private $debugFunctions;

    public function __construct() {
        $this->debugFunctions = array(
            "testing" => function()
            {
                return "I'm a test function!";
            },
            "foo" => function()
            {
                return "bar";
            }
        );
    }
}
有关原因的解释,请参见:类属性必须是常量并且在编译时已知。如果需要它是动态的或更复杂的,可以在实例初始化期间(在构造函数中)填充它。

您可以这样做

只需在构造函数中初始化它:

function __construct() {
    $debugFunctions = array(
        "testing" => function() // Line 87
        {
            return "I'm a test function!";
        },
        "foo" => function()
        {
            return "bar";
        }
    );
}

我猜这是因为它在一个类中,并且与此相关:它在一个类之外的普通数组中工作吗?这散发着PHP设计缺陷的味道。。。但是,函数在PHP中并不是真正的第一类公民。您是否尝试过在构造函数中而不是直接在类定义中执行此赋值?与往常一样:运行时信息不能在运行时之前分配给属性。lambda是Closure类的实例。您也不能将实例作为声明的属性。如果你想让lambdas出现在那里,你必须从屏幕上添加它们,这肯定会起作用,但他展示的方式可能会更好。真糟糕,这样做是不可能的。我想有人在跟踪我,否决了我所有的问题。他们没那么蠢。