PHP 空构造函数
只是想知道在 PHP 中最好定义一个空构造函数还是完全保留构造函数定义?我习惯于仅使用 return true;
来定义构造函数,即使我不需要构造函数执行任何操作 - 只是出于完成原因。
Just wondering is it best to define an empty constructor or leave the constructor definition out completely in PHP? I have a habit of defining constructors with just return true;
, even if I don't need the constructor to do anything - just for completion reasons.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果不需要构造函数,最好将其省略,无需编写更多代码。当你写它时,将其留空......返回 true 没有目的。
If you don't need a constructor it's best to leave it out, no need to write more code. When you DO write it, leave it empty... returning true doesn't have a purpose.
两者之间有一个区别:如果您编写一个空的
__construct()
函数,则会覆盖从父类继承的任何__construct()
函数。因此,如果您不需要它并且不想显式覆盖父构造函数,则根本不要编写它。
There is a difference between the two: If you write an empty
__construct()
function, you overwrite any inherited__construct()
from a parent class.So if you don't need it and you do not want to overwrite the parent constructor explicitly, don't write it at all.
编辑:
以前的答案不再有效,因为 PHP 现在的行为与其他 oop 编程语言类似。
构造函数不是接口的一部分。因此,您现在可以按照您喜欢的方式覆盖它们,而不会出现任何问题,
唯一的例外是:
以前的旧无效答案:
空构造函数和根本没有构造函数之间存在重要区别
EDIT:
previous answer is no longer valid, since PHP now behaves like other oop programming languages.
constructors aren't part of interfaces. therefore you are now allowed to override them how you prefer without any issues whatsoever
the only exception to this is:
PREVIOUS OLD NOT-VALID-ANYMORE ANSWER:
there is an important difference between an empty constructor and no constructor at all
如果你的对象永远不应该被实例化,你应该只定义一个空的构造函数。如果是这种情况,请将 __construct() 设为私有。
You should only define an empty constructor if your object should never be instantiated. If that is the case, make the
__construct()
private.构造函数总是返回定义它的类的实例。因此,您永远不会在 constructor 内部使用“return”。最后,如果您不打算使用它,最好不要定义它。
constructor always return instance of class in which its defined . Hence you never use "return" inside constructor . Lastly its better not to define it if you are not gona use it .
您可能想要定义空构造函数的原因之一是您想要避免调用具有相同类名的函数。
这是由于 PHP 4 的向后兼容性,其中构造函数具有与类相同的名称。
无论如何,它在 PHP 7.4.26 中已被弃用。
One reason you might want to define an empty constructor is when you want to avoid calling a function that has the same class name.
This is due PHP 4 backwards compatibility, where constructors had the same name of the class.
Anyway it got deprecated in PHP 7.4.26.