For example, I have such a code:
<?php
$A = array(
    'echoSmth' => function(){ 
        echo 'Smth';
    }
);
$A['echoSmth']();  // 'Smth'
?>
It works fine! But If $A is not just a variable, but a Class method - than this doesn't work:
<?php
class AA {
    public $A = array(
        'echoSmth' => function(){ // Parse Error here!
            echo 'Smth';
        }
    );
}
// Fixed call:
$t = new AA();
$t->A['echoSmth']();
// no matter what call, because error occurs early - in describing of class
?>
Why doesn't it work?
It displays:
Parse error: syntax error, unexpected T_FUNCTION
P.S. Sorry, I've made some mistakes in the way I call the method, I was in hurry. But there's no matter how I call. Error ocurrs even if I just declare class, without calling
As far as I'm aware, you can't have anything dynamic when defining a class member, you can however set it dynamically as below. So basically, you can't do it for the same reason that you can't do this: public $A = functionname();
Also, your call signature was incorrect, I've fixed it in my example.
<?php
class AA {
    public $A = array();
    public function __construct() {
        $a = function() {
            echo 'Smth';
        };
        $this->A['echoSmth'] = $a;
    }
}
$t = new AA();
$t->A['echoSmth']();
Alternatively, you could define the whole array within __construct(), containing the method (so basically shift your code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With