How to declare functions in an array declared in the block of a class?

1

At a minimum I tried, but PHP throws a syntax error:

  

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

In short, I can not declare functions in my array.

When I create my array $ast out of the block of class PMoon , it works. Is there any other way to declare this array containing functions?

<?php

/* ... */

class PMoon {

    /* ... */

    public $ast = array(

        "labelStatement" => function($label) { // o erro começa aqui
        return array(
            "type" => 'LabelStatement',
            "label" => $label
        );
        }

        /* ... */

    );

    /* ... */
}
    
asked by anonymous 07.08.2016 / 15:13

1 answer

3

According to the PHP properties page, this is because:

  

[...] They are defined using one of the keywords public , protected , or    private , followed by a normal variable declaration. It is   statement may include your initialization, however this initialization   should be a constant value - that is, it should be possible to evaluate it in   compilation time and should not depend on   execution .

One way to resolve this is to use array in the __construct method:

class PMoon{
    public $ast = array();

    public function __construct(){
        $this->ast = array('labelStatement' => 
        create_function('$label', 'return array("type" => "LabelStatement", 
                                                "label" => $label);'
        )); 
    }
}

And to use it, do so:

$moon = new PMoon;
$labelFunc = $moon->ast['labelStatement']('Foo bar');

var_dump($labelFunc);

//array(2) {
//  ["type"]=>
//  string(14) "LabelStatement"
//  ["label"]=>
//  string(7) "Foo bar"
//}

See demo

    
07.08.2016 / 16:38