Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple paamayim nekudotayims in PHP, why not?

In PHP 5.3.6, I've noticed that the following won't work:

class Foo{
    public static $class = 'Bar';
}

class Bar{
    public static function sayHello(){
        echo 'Hello World';
    }
}

Foo::$class::sayHello();

Issuing an unexpected T_PAAMAYIM_NEKUDOTAYIM. Using a temporary variable however, results in the expected:

$class = Foo::$class;
$class::sayHello(); // Hello World

Does anyone know if this is by design, or an unintended result of how the scope resolution operator is tokenized or something? Any cleaner workarounds than the latter, temporary variable example?

like image 494
Dan Lugg Avatar asked Jul 08 '11 02:07

Dan Lugg


1 Answers

Unfortunately there is no way to do it in one line. I thought you might be able to do it with call_user_func(), but no go:

call_user_func(Foo::$class.'::sayHello()');
// Warning: call_user_func() expects parameter 1 to be a valid callback, class 'Bar' does not have a method 'sayHello()'

Also, why would you want to do something like this in the first place? I'm sure there must be a better way to do what you're trying to do - there usually is if you're using variable variables or class names.

like image 74
Mike Avatar answered Oct 14 '22 08:10

Mike