开发者

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

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!
      开发者_JS百科      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).


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.


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

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜