为什么函数作为数组项在php类不工作


Why function as array item in php class doesn't work

例如,我有一个代码:

<?php
$A = array(
    'echoSmth' => function(){ 
        echo 'Smth';
    }
);
$A['echoSmth']();  // 'Smth'
?>

它工作得很好!但是如果$A不仅仅是一个变量,而是一个类方法,那么这就不起作用了:

<?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
?>

为什么不工作?它显示:Parse error: syntax error, unexpected T_FUNCTION

注:对不起,我在调用方法的方式上犯了一些错误,我太匆忙了。但不管我怎么打电话。即使我只是声明类,没有调用

,也会发生错误

据我所知,在定义类成员时,你不能有任何动态的东西,但是你可以像下面这样动态地设置它。所以基本上,你不能这样做的原因和你不能这样做的原因是一样的:public $A = functionname();

另外,你的呼叫签名不正确,我已经在我的例子中修复了它。

<?php
class AA {
    public $A = array();
    public function __construct() {
        $a = function() {
            echo 'Smth';
        };
        $this->A['echoSmth'] = $a;
    }
}
$t = new AA();
$t->A['echoSmth']();

或者,您可以在__construct()中定义整个数组,包含该方法(因此基本上更改了代码)。

我让这个工作。不知道为什么不允许直接声明。

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

编辑:我也看到并纠正了$t->$a首先,但我需要移动声明以及使其工作。

好吧,它有点工作…

<?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']();
?>