HomePHP Page 2 - Using Method Call Overloading in PHP 4
Going backwards: a quick look at a previous example - PHP
This is part two of the series “Overloading classes in PHP.” In three tutorials, this series teaches how to overload your classes in PHP 4 by using the “overload()” PHP built-in function, in conjunction with the implementation of the “__set()”, “__get()” and “__call()” methods, and explores the native support of object overloading in PHP 5.
Before I explain how to combine the two “__set()” and “__get()” methods within the same overloaded class, you should take a brief look at the sample “CookieSaver” class that I wrote in the first article, which provides a concrete implementation of the “__set()” method. Here is the signature of this class, according to its original definition:
class CookieSaver{ var $cookieName; var $value; var $expTimes=array('exp1'=>900,'exp2'=>1800,'exp3'=>3600); function CookieSaver ($cookieName='defaultCookie',$value='defaultValue'){ if(!is_string($cookieName)){ trigger_error('Invalid cookie name',E_USER_ERROR); } $this->cookieName=$cookieName; $this->value=$value; } // set cookie function setCookie(){ setcookie($this->cookieName,$this->value); } // get cookie function getCookie(){ if(!$cookie=$_COOKIE[$this->cookieName]){ trigger_error('Error retrieving cookie',E_USER_ERROR); } return $cookie; } // set value of property via __set() method function __set($property,$value){ $this->expTimes[$property]=$value; $expTime=$this->expTimes[$property]; setcookie('newCookie',urlencode('This cookie has been set via the __set() method'),time()+$expTime); echo 'Setting new cookie...with an expiration of '.$expTime.' seconds.'; return; } }
Assuming that the above class is now fresh in your mind, below I listed a simple script that triggers the “_set()” method when a property access is overloaded. Take a look please:
// instantiate 'CookieSaver' object $cookieSaver=&new CookieSaver(); // set cookie $cookieSaver->setCookie(); // call __set() method and modify $this->expTimes['exp1'] array element @$cookieSaver->exp1=3600;
In this case, the previous code sample demonstrates a crude implementation of how to overload a property access, in order to automatically run the code defined inside the __”set()” method. After running the previous script, its output is the following:
Setting new cookie...with an expiration of 3600 seconds.
Now that you remember how to call a “__set()” method, and also a “__get()” method via the corresponding overloading of a property access, let’s see how both methods can be combined inside the same “CookieSaver” class. To learn how this will be done, please read the following section of the article.