php - How to access multiple properties with magic method(__get & __set)? -
i studied magic methods, __get
, __set
, , wondering how set , multiple properties in class.
i know works 1 variable or array, i'm not sure accessing multiple variables.
is there explain 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 way access variables ($data
, $name
, $age
)?
when work @ projects have these methods:
public function __set($name, $value) { //see if there exists setter method: setname() $method = 'set' . ucfirst($name); if(!method_exists($this, $method)) { //if there no setter, receive public/protected vars , set correct 1 if found $vars = $this->vars; if(array_search("_" . $name, $vars) !== false) $this->{"_" . $name} = $value; } else $this->$method($value); //call setter value } public function __get($name) { //see if there getter method: getname() $method = 'get' . ucfirst($name); if(!method_exists($this, $method)) { //if there no getter, receive public/protected vars , return correct 1 if found $vars = $this->vars; if(array_search("_" . $name, $vars) !== false) return $this->{"_" . $name}; } else return $this->$method(); //call 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) $var) { $this->_vars[] = $var->name; } } return $this->_vars; }
so them give myself freedom create setter/getter properties if want manipulate them before writing/returning. if no setter/getter exists property falls property itself. method getvars() receive public , protected properties class.
my class properties defined underscorce should change that.
Comments
Post a Comment