2013-10-08 41 views
0

我看到自己在做這個有很多:我應該強制記憶嗎?

function getTheProperty() 
{ 
    if (! isset($this->theproperty)) { 
     $property = // logic to initialise thepropery 
     $this->theproperty = $property; 
    } 
    return $this->theproperty; 
} 

這是好事,因爲它避免了用於初始化值的epxensive邏輯。然而,我所看到的不利之處在於,我無法確定客戶端如何使用這個,這可能會讓人困惑。

這是一個很好的使用模式嗎?在做這件事時應該考慮什麼?

如何添加一個參數 - 例如$ forceNew繞過記憶?

回答

0

Magic Methods。例如:

Class MyMagic { 

    private $initinfo = array(
    'foo' => array('someFunction', array('arg1', 'arg2')) 
    'bar' => array(array($this, 'memberFunction'), array('arg3')) 
); 

    public function __get($name) { 
    if(! isset($this->$name)) { 
     if(isset($this->initinfo[$name])) { 
     $this->$name = call_user_func_array(initinfo[$name][0], initinfo[$name][1]); 
     } else { 
     throw new Exception('Property ' . $name . 'is not defined.'); 
     } 
    } else { 
     return $this->$name; 
    } 
    } 

} 

$magic = new MyMagic(); 
echo $magic->foo; //echoes the return of: someFunction('arg1', 'arg2') 
echo $magic->bar; //echoes the return of: $this->memberFunction('arg3') 
+0

昂貴的方面需要大量的工作/時間來傳遞價值。也許是大數據庫讀取,API調用等。 –

+0

我不太喜歡你的代碼示例。抱歉。 –

+0

@MartyWallace是的,我剛剛讀了關於memoization [我認爲這是一個錯字]讓我重新寫這個答案。 – Sammitch

相關問題