2014-10-29 50 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; 
    } 

} 

吸气只给你一个对象在第一时间就被称为!