2014-10-29 63 views
-1

我想完成我的代碼的語法如下:PHP的OOP代碼語法,未使用的情況下

$data = new Data(); 
$user = $data -> user -> get(1); 
$product = $data -> product -> get(1); 

使用:

class Data { 

    public $user = null; 
    public $product = null; 
    public $a = null; 
    ... 

    function __construct() {   
     this -> user = new User(); 
     this -> product = new Product(); 
     this -> a = new A(); 
     ... 
    } 

} 

與代碼的問題是,我將有數據類中有大量未使用的實例,因爲我不會在特定場景中全部使用它們。我怎樣才能防止這一點?

+3

簡單。不要使用該代碼。相反,查看工廠和單身人士。 – 2014-10-29 16:36:21

+0

用'__get()'重載,或者更改爲不需要實例化未使用對象的設計。工廠是完全可以的,小心Singleton中的全局作用域,實際上,如果'Data'類需要'User'或者'Product',那麼通常需要確保依賴注入類擁有它們,如果你想讓它們在那裏。 – Wrikken 2014-10-29 16:37:13

+0

@SergiuParaschiv我正在使用與LS11小改動相同的代碼。 – lolol 2014-10-29 17:29:26

回答

2

在一個非常基本的層面上,你可以做這樣的事情,你爲用戶屬性定義一個getter,並且該對象只在第一次調用時才被實例化。

class Data { 

    protected $user = null; 

    public function user() 
    { 
     if ($this->user === null) { 
      $this->user = new User(); 
     } 
     return $this->user; 
    } 

} 
+0

好主意:'$ data - > user() - > get(1);'? – lolol 2014-10-29 16:44:03

0

你可以使用聚合,這意味着你傳遞一個對象入類,這樣的類越來越null或對象,你通過一次不進行初始化一切節省資源。​​(不是我的)。

它基本上是這樣的:

class Test { 
    public $a = ''; 

    public function __construct($object) { 
    $this->a = $object; 
    } 
} 
0

我會說你可以嘗試這樣的事:

class ThisOne{ 

    protected $user = null; 

    public function user() 
    { 
     if ($this->user === null) { 
      $this->user = new User(); 
     } 
     return $this->user; 
    } 

} 

吸氣只給你一個對象在第一時間就被稱爲!

相關問題