2012-12-11 39 views
-1

我有一個類'base'和一個類'loader',看起來像這樣。__get和__set不可訪問的魔法方法

class base { 

    protected $attributes = Array(); 
    public $load = null;   

    function __construct() { 

     $this->load = loader::getInstance(); 
     echo $this->load->welcome(); //prints Welcome foo 
     echo $this->load->name; //prints Foo 
     echo $this->name; //doesnt print anything and i want it to print Foo 

    } 


    public function __get($key) { 

     return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null; 
    } 

    public function __set($key, $value) { 

     $this->attributes[$key] = $value; 
    } 
} 

class loader { 

    private static $m_pInstance;  

    private function __construct() { 

     $this->name = "Foo"; 

    } 

    public static function getInstance() { 
     if (!self::$m_pInstance) { 
      self::$m_pInstance = new loader(); 
     } 

     return self::$m_pInstance; 
    } 

    function welcome() { 
     return "welcome Foo"; 
    } 

} 

$b = new base(); 

現在,我要的是存儲從裝載機類變量和使用$this->variablename從基類訪問它們的方式。

我該如何做到這一點?我不想使用extends。任何想法 ?

+0

您的'loader'類實例應該通過'base'的構造函數傳入。 –

+0

我通過使用$ this-> load = loader :: getInstance();將基類變量'load'中的加載器類實例保存起來。 –

+1

這不一樣;通過構造函數傳遞它更清潔。 –

回答

1

你__get/__ set方法訪問它訪問$this->attributes但不$this->load
你可以例如這樣做(僞)

function __get($key) { 
    - if $attribute has an element $key->$value return $attribute[$key] else 
    - if $load is an object having a property $key return $load->$key else 
    - return null; 
} 

還看到:http://docs.php.net/property_exists

+0

謝謝@VolkerK。那正是我正在尋找的。 +1 –

0

可以使靜態變量,然後你可以從任何地方

public statis $var = NULL; 

訪問這個變量,你可以這樣

classname::$var; 
+0

這不是如何OOP去... – Shoe

2

我不覺得自己已經完全理解了OOP方式意味着什麼編碼。通常單身人士是代碼氣味,所以我只是警告你:

有可能是一個更好的方式來實現你的目標。如果您提供更多信息,我們將爲您提供幫助。目前的答案如下:只記得我的極力阻止它在你的代碼中的實現。

假設你要訪問的唯一的公共(和非靜態)loader的變量this->varnamebase類,你應該只需要插入這條線在基類的構造函數的開頭:

$this->attributes = get_object_vars(loader::getInstance()); 

這將基本上初始化屬性數組與所有的裝載機公共變量,以便通過您的__get()方法,您可以訪問其值。

在旁註中,請看Dependency Injection design pattern以避免使用單件。

+0

作爲對此的擴展,在這種情況下,您應該傳遞「基礎」所需的「加載器」的確切變量。這些通用名稱也暗示了代碼味道,它們到底是什麼? –

相關問題