Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 309
Larry Cinnabar Avatar asked Apr 30 '11 14:04

Larry Cinnabar


1 Answers

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

like image 146
Rudi Visser Avatar answered Sep 20 '22 06:09

Rudi Visser