Jump to content

Question about using __get()


eldan88

Recommended Posts

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';	
}
Link to comment
https://forums.phpfreaks.com/topic/281545-question-about-using-__get/
Share on other sites

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.

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.