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

Asked

Viewed 33 times

1

At least I tried, but PHP plays a syntax error:

Parse error: syntax error, Unexpected 'Function' (T_FUNCTION)

In short, I cannot declare functions in my array.

When I create my array $ast outside the class block PMoon, works. There is some 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
        );
        }

        /* ... */

    );

    /* ... */
}

1 answer

3


According to the page of PHP on properties, this happens because:

[...] Are defined using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include its initialization, but this initialization should be a constant value - that is, it should be possible to evaluate it in compile time and should not be dependent on time information of execution.

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

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 demonstration

Browser other questions tagged

You are not signed in. Login or sign up in order to post.