Dynamic Getter/Setters for PHP
November 23rd, 2007
We use the magic __call method in PHP which is called on an object when a declared function is called on it but it does not exist. This behaviour allows us to have default getters/setters but if we want specific behaviour for a get/set we just have to add the function to the class and __call will no longer be used for that class attribute.
class GetSetExample{/*** Dynamic getters and setters than maintain getX and setX formati. They can be overwritten* if custom processing is needed** @param string $method* @param array $arguments* @return mixed*/function __call($method, $arguments) {#Is this a get or a set$prefix = strtolower(substr($method, 0, 3));#What is the get/set class attribute$property = substr($method, 3);if (empty($prefix) || empty($property)) { #Did not match a get/set callthrow New Exception("Calling a non get/set method that does not exist: $method");}#Check if the get/set paramter exists within this class as an attribute$match=false;foreach($this as $class_var=>$class_var_value){if(strtolower($class_var) == strtolower($property)){$property=$class_var;$match=true;}}#Get attributeif ($match && $prefix == "get" && isset($this->$property)) {return $this->$property;}#Setif ($match && $prefix == "set") {$thisi->$property = $arguments[0];}elseif (!$match && $prefix == "set"){throw new Exception("Setting a variable that does not exist: var:$property value: $arguments[0]");}else{throw new Exception("Calling a get/set method that does not exist: $property");}}}
Leave a Reply