eldan88 Posted August 25, 2013 Share Posted August 25, 2013 Hey, I have been learning about magic methods, and I am little bit confused about how the __get() methods works below. I don't understand the code that goes below the comment "//Attempt to return a protected property by name" How does it know what property name to return?? function __get($name) { //Postal code look up if unset if(!$this->_postal_code) $this->_postal_code = $this->_postal_code_guess(); //Attempt to return a protected property by name $protected_property_name = "-" . $name; if(property_exists($this, $protected_property_name)) { return $this->$protected_property_name; } //Unable to access property trigger error trigger_error('Undefined property via __get:', $name); return NULL; } protected function _postal_code_guess() { return 'LOOKUP'; } Quote Link to comment Share on other sites More sharing options...
kicken Posted August 25, 2013 Share Posted August 25, 2013 It generates the name by concatenating '-' with $name. $name will be the name of the property which was trying to be accessed. For example: $obj=new MagicObject; echo $obj->SomeProperty; If there is no SomeProperty variable defined in class MagicObject (or it is inaccessible due to visibility rules), php will try to access it by calling __get('SomeProperty'), as if that code were re-written to: $obj=new MagicObject; echo $obj->__get('SomeProperty'); So in the __get code from your post, what happens is $protected_property_name gets set to the value '-'.$name; resulting in -SomeProperty. Then it checks if that variable exists on the object and if so, returns it. Quote Link to comment Share on other sites More sharing options...
eldan88 Posted August 29, 2013 Author Share Posted August 29, 2013 It generates the name by concatenating '-' with $name. $name will be the name of the property which was trying to be accessed. For example: $obj=new MagicObject; echo $obj->SomeProperty; If there is no SomeProperty variable defined in class MagicObject (or it is inaccessible due to visibility rules), php will try to access it by calling __get('SomeProperty'), as if that code were re-written to: $obj=new MagicObject; echo $obj->__get('SomeProperty'); So in the __get code from your post, what happens is $protected_property_name gets set to the value '-'.$name; resulting in -SomeProperty. Then it checks if that variable exists on the object and if so, returns it. Oh okay! I got it now... I am getting used to how magic methods works. Thanks for the clear explination! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.