首页 > 解决方案 > PHP后期绑定静态与私有__construct

问题描述

我有一个抽象类,它有一个使用 PHP 的后期静态绑定的函数,如下所示:

abstract class MetaComponent {
    public static function do(...$args) {
        return new static(...$args);
    }
}

然后,我以这种方式实现了抽象类:

class ¬Text extends MetaComponent {
    private function __construct(string $text) {
        $this->text = $text;
    }

    public function render() {
        echo $this->text;
    }
}

我的意图是没有人可以¬Text直接实例化,所以我将__construct函数设为私有。但是,任何人都应该能够通过¬Text::do('Lorem Ipsum'). 这就是为什么我在MetaComponent::do().

但是,我收到以下错误:

PHP Fatal error: Uncaught Error: Call to private ¬Text::__construct() from context 'MetaComponent' in /xxx/MetaComponent.php:9

有没有办法从抽象类调用构造函数,同时防止__construct被直接调用?

标签: phpabstract-classlate-static-binding

解决方案


推荐阅读