2011-10-06 107 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()

所以,如果你不需要它,你不想明確地覆蓋父構造函數,不要寫它。