如何在变量类名(它是属性)上调用静态方法?


How can I call a static method on a variable classname that is a property?

如何在变量classname上调用静态方法?

下面是一些示例代码:
class Foo
{
    var $class = 'Bar';
    public function getNew() {
        return $this->class::create(); // this fails
    }
}
class Bar
{
    public static function create() {
        return new self();
    }
}
$foo = new Foo();
$foo->getNew();

在这个例子中,我如何在$class属性中指定的类上调用静态方法?

变量范围解析失败,解析错误:

{$this->class}::create();
($this->class)::create();

这个可以工作,但是太啰嗦了:

$class = $this->class;
$class::create();
call_user_func([$this->class, 'create']);

是否有更短或更可读的方式?我使用PHP 5.6

马克的评论完全正确。如此:

<?php
class Foo {
    var $class = 'Bar';
    public function getNew() {
        $className = $this->class;
        return $className::create();
    }
}
class Bar {
    public static function create() {
        return new self();
    }
    public function speak() {
        echo 'It lives';
    }
}
$foo = new Foo();
$bar = $foo->getNew();
$bar->speak();

但是,不要害怕它冗长,因为它非常清楚。而且PHP还有许多其他冗长的结构需要考虑。