Why function as array item in php class doesn'

2019-03-30 00:04发布

问题:

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

回答1:

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).



回答2:

I got this to work. Not sure why direct declaration is not permitted though.

class AA {
    var $A;
    public function __construct() {
        $this->A = array(
            'echoSmth' => function(){
                echo 'Smth';
            }
        );
    }
}

$t = new AA();
$t->A['echoSmth']();

EDIT: I also saw and corrected $t->$a first, but I needed to move the declaration as well to make it work.



回答3:

well , it kinda works ...

<?php

    class Bleh
    {

        public $f = array();

        public function register( $name , $func )
        {

            $this->f[ $name ] =  $func;

        }

    }   


    $foo = new Bleh;
    $foo->register( 'bar' , function(){ echo 'foobar'; } );

    $foo->f['bar']();

?>