php - 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
被直接调用?
解决方案
推荐阅读
- authentication - Spring security:基于自定义逻辑而不只是 URL 请求登录
- angular - 在 Angular 和 Ionic 项目之间导入服务时,'inject() 必须从注入上下文中调用'
- javascript - Firebase 和 Vuex:为什么用户配置文件文档在页面刷新之前不存在?
- scala - 如何使用 scalac 编译具有依赖项的类?
- c++ - ARM64上的多播“没有这样的设备”?
- docker - 发出 EC2 停止实例时如何使用 docker-compose down 优雅地停止 docker 服务
- java - 使用反射库时出现 UnsupportedClassVersionError: JVMCFRE003 错误
- python - 如何在 Python 中提取一个字典的键和值
- groovy - Nextflow 将提交的输出显示为空
- c - 我怎样才能毫不拖延地“延迟节目”?