只是想知道是最好定义一个空的构造函数还是将构造函数定义完全留在PHP中?我习惯用return true;
来定义构造函数,即使我不需要构造函数来做任何事情 - 仅仅是出于完成的原因。PHP空构造函数
Q
PHP空构造函数
8
A
回答
10
如果你不需要构造函数,最好不要写它,不需要编写更多的代码。当你写它时,把它留空...返回true没有目的。
1
构造函数总是返回其定义的类的实例。因此,你永远不会在构造函数中使用“return”。最后最好不要定义它,如果你不是使用它。
2
如果你的对象永远不会被实例化,你应该只定义一个空构造函数。如果是这种情况,请将__construct()
私有。
5
编辑:
以前的答案是不再有效,因为PHP现在的行为像其他OOP编程语言。 构造函数不是接口的一部分。因此,你现在允许你怎么没有任何问题喜欢任何
唯一的例外覆盖它们是:
interface iTest
{
function __construct(A $a, B $b, Array $c);
}
class Test implements iTest
{
function __construct(A $a, B $b, Array $c){}
// in this case the constructor must be compatible with the one specified in the interface
// this is something that php allows but that should never be used
// in fact as i stated earlier, constructors must not be part of interfaces
}
上一个旧的不去化有效了答案:
有是一个空的构造函数和没有构造函数之间的重要区别
class A{}
class B extends A{
function __construct(ArrayObject $a, DOMDocument $b){}
}
VS
class A{
function __construct(){}
}
class B extends A{
function __construct(ArrayObject $a, DOMDocument $b){}
}
// error B::__construct should be compatible with A constructor
+0
不仅如此,但如果'A'有一个定义的构造函数,而'B'有一个定义的空构造函数,那么你基本上就是要移除该构造函数,但是如果你完全放弃它,那么你继承了父项构造函数。结果是,你不应该“总是”或“从不”包含一个空的构造函数,而且当你做一个或另一个时,它不会“总是”意味着同样的事情。这完全取决于上下文。 – Jason
3
这两者之间有区别:如果您编写一个空的__construct()
函数,则会覆盖父类中的所有继承的__construct()
。
所以,如果你不需要它,你不想明确地覆盖父构造函数,不要写它。
相关问题
- 1. 隐式构造函数与“空”构造函数
- 2. PHP:函数像数组构造函数
- 3. php oop构造函数
- 4. php typecast构造函数
- 5. PHP构造函数单PARAM
- 6. Firebase的数据类空构造函数
- 7. String类中的空构造函数
- 8. 扩展片段的空构造函数
- 9. 空的构造函数的必要性
- 10. 没有空的构造函数
- 11. C++空字符串构造函数
- 12. 申报空/默认构造函数
- 13. 默认构造函数与空括号
- 14. C++中的空构造函数:
- 15. 空的构造函数和没有构造函数有什么区别
- 16. 构造函数中的调用基构造函数和其他构造函数
- 17. 如何让父类构造函数在子构造函数之前运行? (PHP)
- 18. C++ - 构造函数,复制构造函数,移动构造函数,析构函数
- 19. PHP-Codeigniter中的构造函数
- 20. Imagick构造函数崩溃PHP/CGI
- 21. PHP - 构造函数不返回false
- 22. PHP构造函数调用语法
- 23. PHP构造函数不似乎工作
- 24. PHP SoapClient构造函数极其缓慢
- 25. PHP - init父变量(带构造函数)
- 26. PHP中的jQuery风格构造函数
- 27. PHP调用构造函数一次
- 28. PHP:在构造函数中使用$ this
- 29. PHP构造函数返回NULL
- 30. 无参数构造函数调用2参数构造函数
构造函数的返回值被完全忽略。 – KingCrunch
的确,如果我发现有人在构造函数中首先返回,我永远不会将他的代码与我的代码合并。 –