Function literal in PHP class

一曲冷凌霜 提交于 2019-11-28 09:07:40

问题


Take a look at this code, please:

$array = array(
    'action' => function () { echo "this works"; }
);

class Test {
    public $array = array(
        "action" => function () { echo "this doesn't"; }
    );
}

The first function literal parses fine, but the second - the one inside the class - triggers a syntax error:

Parse error: syntax error, unexpected 'function' (T_FUNCTION)...

Can somebody explain this to me? Is this a bug?

EDIT: This is the latest PHP: 5.6.6


回答1:


From the class it's a property !

Rule from properties :

Declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

http://php.net/manual/en/language.oop5.properties.php




回答2:


I dont have chance to test Your code on PHP 5.6.6, but I think this code resolve Your problem.

class Test{

    public $array;

    function __construct(){

            $this -> array = array(

                'action'    =>  function (){

                    echo 'It works too';
                }
            );
    }
}

$test = new Test();
$test -> array['action']();



回答3:


Try it like this, let me know if this works for you

<?php
$array = array('action' => function () { echo "this works"; });
class Test {
    public $arr;
    function __construct() {
        $this->arr = array("action" => function () { echo "this works too"; });
    }
    function getArr(){
        var_dump($this->arr);
    }
}

var_dump($array);
$obj = new Test();
$obj->getArr();


来源:https://stackoverflow.com/questions/28832708/function-literal-in-php-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!