Why can#39;t I overload constructors in PHP?(为什么我不能在 PHP 中重载构造函数?)
问题描述
我已经放弃了在 PHP 中重载构造函数的所有希望,所以我真正想知道的是为什么.
I have abandoned all hope of ever being able to overload my constructors in PHP, so what I'd really like to know is why.
有什么原因吗?它是否会创建本质上不好的代码?是被广泛接受的语言设计不允许,还是其他语言比 PHP 更好?
Is there even a reason for it? Does it create inherently bad code? Is it widely accepted language design to not allow it, or are other languages nicer than PHP?
推荐答案
您不能在 PHP 中重载任何方法.如果您希望能够在传递多个不同参数组合的同时实例化 PHP 对象,请使用带有私有构造函数的工厂模式.
You can't overload ANY method in PHP. If you want to be able to instantiate a PHP object while passing several different combinations of parameters, use the factory pattern with a private constructor.
例如:
public MyClass {
private function __construct() {
...
}
public static function makeNewWithParameterA($paramA) {
$obj = new MyClass();
// other initialization
return $obj;
}
public static function makeNewWithParametersBandC($paramB, $paramC) {
$obj = new MyClass();
// other initialization
return $obj;
}
}
$myObject = MyClass::makeNewWithParameterA("foo");
$anotherObject = MyClass::makeNewWithParametersBandC("bar", 3);
这篇关于为什么我不能在 PHP 中重载构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能在 PHP 中重载构造函数?


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01