Search code examples
phpclassmagic-methods

__get and __set magic methods not accessible


I have a class 'base' and a class 'loader', which looks like this.

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();

Now what I want is a way to store variables from loader class and access them from base class using $this->variablename.

How can I achieve this? I don't want to use extends. Any idea ?


Solution

  • Your __get/__set methods access $this->attributes but not $this->load.
    You could e.g. do something like (pseudocode)

    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;
    }
    

    see also: http://docs.php.net/property_exists