2011-10-06 128 views
8

只是想知道是最好定义一个空的构造函数还是将构造函数定义完全留在PHP中?我习惯用return true;来定义构造函数,即使我不需要构造函数来做任何事情 - 仅仅是出于完成的原因。PHP空构造函数

回答

10

如果你不需要构造函数,最好不要写它,不需要编写更多的代码。当你写它时,把它留空...返回true没有目的。

1

构造函数总是返回其定义的类的实例。因此,你永远不会在构造函数中使用“return”。最后最好不要定义它,如果你不是使用它。

+0

构造函数的返回值被完全忽略。 – KingCrunch

+0

的确,如果我发现有人在构造函数中首先返回,我永远不会将他的代码与我的代码合并。 –

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()

所以,如果你不需要它,你不想明确地覆盖父构造函数,不要写它。