开发者

Multiple paamayim nekudotayims in PHP, why not?

开发者 https://www.devze.com 2023-03-17 23:22 出处:网络
In PHP 5.3.6, I\'ve noticed that the foll开发者_如何转开发owing won\'t work: class Foo{ public static $class = \'Bar\';

In PHP 5.3.6, I've noticed that the foll开发者_如何转开发owing 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?


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.

0

精彩评论

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

关注公众号