2014-02-21 42 views
1

我很少在PHP中使用類,所以原諒我的無知。類實例化的NULL參數

我已經有了一個帶有返回值的函數。在課程開始時,我有一個構造函數用於創建類函數中使用的變量。像這樣:

function __construct($firstVariable,$secondVariable,$thirdVariable) { 

    if(isset($firstVariable)) { $this->firstname = $first; }; 
    if(isset($secondVariable)) { $this->secondname = $second; }; 
    if(isset($thirdVariable)) { $this->thirdname = $third; }; 
} 

我的問題是這樣的:如果我只打算使用$secondVariable?我知道我可以在課堂實例化時進行以下操作:

$Class = new classname(NULL,$secondVariable,NULL); 

但是我覺得這樣做不合適或效率低下。使用這種方法,我每次不想使用變量時,我實際上需要通過NULL ......這將會發生很多,因爲我在頁面之間使用類的變體。例如,頁面#1使用第二個參數,但頁面#2使用第三個參數。 #3使用全部三種。

所以......

#1: $Class = new classname(NULL,$secondVariable,NULL); 
#2: $Class = new classname(NULL,NULL,$thirdVariable); 
#3: $Class = new classname(#firstVariable,$secondVariable,$thirdVariable); 

嗯,這是偉大的和所有,但如果我在需要其自己的變量,因此第四參數類中添加新的功能。我需要返回並添加'NULL'作爲所有類實例的第四個參數,因爲這個新函數沒有被使用(並且由於類需要第四個參數而導致php拋出錯誤)。當然,這不能成爲PHP的最佳實踐!

回答

3

這應該工作,我想?

function __construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL) { 
    if(isset($firstVariable)) { $this->firstname = $first; }; 
    if(isset($secondVariable)) { $this->secondname = $second; }; 
    if(isset($thirdVariable)) { $this->thirdname = $third; }; 
} 

然後,如果您添加更多參數,它們將默認爲NULL,除非另有說明。但請注意,即使是空字符串也會覆蓋默認的NULL。

因此,對於僅使用$secondVariable的示例,您可以這樣做:$Class = new classname(NULL,$secondVariable);。其餘的將默認爲NULL。

如果再改變了功能,包括更多的變量:

function _construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL,$fourthVariable=NULL) { 

它不會造成任何問題。

+0

這適用於我!我的代碼現在效率更高,更容易出錯。我唯一的煩惱是,我需要至少爲參數使用前的所有參數指定NULL ...這是一個障礙,但我認爲這是不可避免的,除非我使用另一個評論中描述的'工廠方法'。 –

+0

@ChrisScott是的,我不認爲有任何其他的方式。如果你覺得它適合你,那麼將會被讚賞爲答案:) – BT643

1

您可以使用默認參數來滿足您的需求。

看到LIVE demo

function __construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL) { 

    if(isset($firstVariable)) { $this->firstname = $first; }; 
    if(isset($secondVariable)) { $this->secondname = $second; }; 
    if(isset($thirdVariable)) { $this->thirdname = $third; }; 
} 
1

如果你想從最後的參數跳到第一,使用BT643的答案。但是,如果您只想使用第二個並跳過上一個,則應該使用factory method pattern

class YourClass { 
    function __construct($firstVariable,$secondVariable,$thirdVariable) { 
    // define the object here 
    } 

    static function createWithSecond($secondVariable) { 
    return new YourClass(NULL,$secondVariable,NULL); 
    } 
} 

// the client code 
$obj1 = new YourClass(1,2,3); // use constructor 
$obj2 = YourClass::createWithSecond(2); // use factory method