2011-10-02 58 views
0

如果我有一個類將被實例化,需要引用每個類相同的數據和/或函數。如何來處理,以遵循正確的編程實踐應該將所有類實例化中相同的數據保存在單獨的靜態類中嗎?

例子(PHP):

class Column { 
    $_type = null; 
    $_validTypes = /* Large array of type choices */; 

    public function __construct($type) { 
     if(type_is_valid($type)) { 
      $_type = $type; 
     } 
    } 

    public function type_is_valid($type) { 
     return in_array($type, $_validTypes); 
    } 
} 

然後每一個列上創建的時候,它會保持$_validTypes變量。這個變量實際上只需要在內存中定義一次,其中創建的所有列都可以引用一個靜態類的靜態函數type_is_valid,該靜態類將保存$_validTypes變量,只聲明一次。

是一個靜態類的想法,說ColumnHelperColumnHandler一個很好的方式來處理這個?或者有沒有辦法在這個類中保存靜態數據和方法?或者,這是爲每個Column重新定義$_validTypes一個好方法來做事情?

回答

0

一種選擇是爲列配置創建新模型,例如,

class ColumnConfig { 
    private $validTypes; 
    public isValid($type){ 
     return isset($this->validType($type))?true:false; 
    } 
} 

然後,如果您有API添加一次到API,或創建一個全局實例,例如

$cc = new ColumnConfig(); 
class Column { 
    private $cc; 
    function __construct($type){ 
     $this->cc = $this->api->getCC(); // if you have api 
     global $cc; // assuming you have no api, an you create a global $cc instance once. 
     $this->cc = $cc; // <-- this would pass only reference to $cc not a copy of $cc itself. 

     if ($this->cc->isValid($type)){ 
      .... 
     } 
    } 
} 

聽起來像是要走的路。

相關問題