Search code examples
phpmagic-methods

How to access multiple properties with magic method(__get & __set)?


I recently studied magic methods, __get and __set, and was wondering how to actually set and get multiple properties in the class.

I know it works perfectly with only one variable or array, but I'm not sure about accessing multiple variables.

Is there anyone who could explain this to me?

class myMagic2 {
    public $data;
    public $name;
    public $age;

    public function __set($item, $value) {
        $this->item = $value;
    }

    public function __get($item){
        return $this->item;
    }
}

Is there a way to access all variables ($data, $name, $age)?


Solution

  • When i work at projects i always have these methods:

    public function __set($name, $value) 
    {
        //see if there exists a extra setter method: setName()
        $method = 'set' . ucfirst($name);
        if(!method_exists($this, $method))
        {
            //if there is no setter, receive all public/protected vars and set the correct one if found
            $vars = $this->vars;
            if(array_search("_" . $name, $vars) !== FALSE)
                $this->{"_" . $name} = $value;
        } else
            $this->$method($value); //call the setter with the value
    }
    
    public function __get($name) 
    {
        //see if there is an extra getter method: getName()
        $method = 'get' . ucfirst($name);
        if(!method_exists($this, $method)) 
        {
            //if there is no getter, receive all public/protected vars and return the correct one if found
            $vars = $this->vars;
            if(array_search("_" . $name, $vars) !== FALSE)
                return $this->{"_" . $name};
        } else
            return $this->$method(); //call the getter
        return null;
    }
    
    public function getVars()
    {
        if(!$this->_vars)
        {
            $reflect = new ReflectionClass($this);
            $this->_vars = array();
            foreach($reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED) as $var)
            {
                $this->_vars[] = $var->name;
            }
        }
        return $this->_vars;
    }
    

    So with them i give myself the freedom to create extra setter/getter for properties if i want to manipulate them before writing/returning. If no setter/getter exists for the property it falls back to the property itself. With the method getVars() you receive all public and protected properties from the class.

    My class properties are always defined with an underscorce so you should probably change that.