CHAPTER 4 – Property and Method Overloading

4.2.1 Property and Method Overloading PHP allows overloading of property access and method calls by implementing special proxy methods that are invoked if the relevant property or method doesn't exist. This gives you a lot of flexibility in intercepting these actions and defining your own functionality. You may implement the following method prototypes: function __get($property) function __set($property, $value) function __call($method, $args) __get is passed the property's name, and you should return a value. __set is passed the property's name and its new value. __call is passed the method's name and a numerically indexed array of the passed arguments starting from 0 for the first argument. The following example shows how to use the __set and __get functions (array_key_exists() is covered later in this book; it checks whether a key exists in the specified array): class StrictCoordinateClass { private $arr = array('x' => NULL, 'y' => NULL); function __get($property) { if (array_key_exists($property, $this->arr)) { return $this->arr[$property]; } else { print "Error: Can't read a property other than x & yn"; } } function __set($property, $value) { if (array_key_exists($property, $this->arr)) { $this->arr[$property] = $value; } else { print "Error: Can't write a property other than x & yn"; } } } $obj = new StrictCoordinateClass(); $obj->x = 1; print $obj->x; print "n"; $obj->n = 2; print $obj->n; The output is 1 Error: Can't write a property other than x & y Error: Can't read a property other than x & y As x exists in the object's array, the setter and getter method handlers agrees to read/write the values. However, when accessing the property n, both for reading and writing, array_key_exists() returns false and, therefore, the error messages are reached. __call() can be used for a variety of purposes. The following example shows how to create a delegation model, in which an instance of the class Hel- loWorldDelegator delegates all method calls to an instance of the HelloWorld class: class HelloWorld { function display($count) { for ($i = 0; $i < $count; $i++) { print "Hello, Worldn"; } return $count; } } class HelloWorldDelegator { function __construct() { $this->obj = new HelloWorld(); } function __call($method, $args) { return call_user_func_array(array($this->obj , $method), $args); } private $obj; } $obj = new HelloWorldDelegator(); print $obj->display(3); This script's output is Hello, World Hello, World Hello, World 3 The call_user_func_array() function allows __call() to relay the function call with its arguments to HelloWorld::display() which prints out "Hello, Worldn" three times. It then returns $count (in this case, 3) which is then printed out. Not only can you relay the method call to a different object (or handle it in whatever way you want), but you can also return a value from __call(), just like a regular method.

Post Comment
Login to post comments