只是想知道最好定义一个空构造函数或者在PHP中完全保留构造函数定义吗?我习惯用just定义构造函数return true;
,即使我不需要构造函数来做任何事情 - 只是为了完成原因.
两者之间存在差异:如果编写空__construct()
函数,则覆盖__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
}
Run Code Online (Sandbox Code Playgroud)
以前的老有效 - 任何以前的答案:
空构造函数和根本没有构造函数之间存在重要区别
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
Run Code Online (Sandbox Code Playgroud)