我有一個類'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
。任何想法 ?
您的'loader'類實例應該通過'base'的構造函數傳入。 –
我通過使用$ this-> load = loader :: getInstance();將基類變量'load'中的加載器類實例保存起來。 –
這不一樣;通過構造函數傳遞它更清潔。 –