Implementing Property Overloading in PHP 4

The object-oriented paradigm includes the ability to overload classes; not surprisingly, this is possible in PHP. In this first part of a series, you will learn how to implement class overloading in PHP 4, specifically using the “overload()” function, which comes in handy for triggering “__set()” and “__get()” methods when a property access is overloaded.

Introduction

If you’ve been working with object-oriented programming in PHP for a considerable time, you probably have a decent grounding in building up classes, defining their methods and properties, as well as implementing several types of object interaction, including aggregation and composition in cases where these techniques are applicable. Additionally, you’ll surely have started using some of the most important foundations of object-based development, such as inheritance and polymorphism.

To return to mastering all the concepts that I deployed before, perhaps you consider yourself an experienced PHP developer that has explored and understood the nitty-gritty of working with objects during the development of different applications. However, luckily for you and me, the object-oriented paradigm always has some additional exciting aspects that might be pretty interesting to expand our overall knowledge of PHP.

That’s precisely the case with the overloading of classes, since PHP comes with a fairly handy support for overloading both method calls and property access of objects, something that can be truly useful when used in a clever way. Certainly, I don’t mean that the implementation of class overloading in PHP is as powerful as you’ll find if you work with C++ or Python, but it definitely can help in the development of more robust code, particularly when you want to combine it with the advantages offered by inheritance.

After introducing the topic, allow me to tell you what you’ll learn during the course of this series, so you won’t suffer the effects of unexpected surprises. In these articles, I’ll explain the basics of class overloading, starting with the application of the “overload()” function in PHP 4, in conjunction with using the “_set()”, __get()” and “__call()” methods, accompanied of several practical examples, so you’ll have a clear idea of how to overload your classes. Also, I’ll cover class overloading in PHP 5, which offers native support for overloading methods and properties through the built-in methods that I mentioned before.

With the preliminaries out of our way, let’s start learning more about how to implement class overloading in PHP. Let’s go!

{mospagebreak title=Overloading a property access: using the “__set()” method}

As you’ll see shortly, PHP 4 comes with the “overload()” function and allows both overloading of object property access and method calls. Once a class has been defined, it’s possible to access and set a property via the “__set()” and “__get()” methods respectively, and even overload a property access via a method call, through the homonymous “__call()” method.

Perhaps this sounds a little confusing to you. Allow me to implement a simple example, which hopefully will help to clarify how class overloading works in PHP 4. To begin with, I’ll define a sample class, which I imaginatively called “CookieSaver.” After defining this class, I’ll show you how property access can be overloaded via the “__set()” method.

So first , here’s the source code of the “CookieSaver()” class:

// define ‘CookieSaver’ class and implement __set() method
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;
    }
}

As shown above, the logic of the “CookieSaver” class is pretty straightforward. Essentially, what it does is set a cookie by using the “$cookieName” and “$value” properties respectively, which are used within the “setCookie()” method. Inversely, the value of this cookie can be retrieved by the pertinent “getCookie()” method, if you’re patient enough and study the code listed above.

So far, the definition of the previous class falls under what you usually expect from a typical class. However, slow down and pay attention to the following method:

// 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;
}

As you can see, the above “__set()” method has been defined, in order to first, modify the value of one specific array element included within the $expTimes property, and second, set a new cookie that takes up this value as its expiration time.

Indeed, what makes this method interesting isn’t how the cookie is set, but how the value of the elements that compose the $expTimes array can be modified through overloading a property access. To put it simply, if you create a class that implements a concrete definition for the “__set()” method, this will be automatically called with the following parameters:

__set($property,$value){
    // method definition goes here
}

However, to make sure this method will be properly called, the class must not contain the property that you’re trying to access. In this example, this condition is met, since the “__set()” method only modifies the elements of the $expTimes array, and not this property directly. Of course, this requirement must be satisfied when using the “__get()” and “__call()” methods too, as you’ll see later on.

All right, now that you know how the “__set()” method has been correctly defined, it’s time to see how a property access can be overloaded. In order to achieve this, PHP 4 uses its “overload()” function, which will be explained in detail in the next section. Therefore, click on the link below and keep reading.

{mospagebreak title=Overloading a PHP 4 class: using the native “overload()” function}

Over the previous section, I created the sample “CookieSaver” class and went through the explanation of its “__set()” method, which comes in handy for modifying the elements of the $expTimes array. After defining the signature of this class, I’ll use the “overload()” function, in order to enable the overloading of its property accesses. The code listed below shows how to overload the “CookieSaver” class:

// overload ‘CookieSaver’ class
overload(‘CookieSaver’);

That’s it. Now, the sample class has been overloaded by the corresponding “overload()” function, which, as you saw, takes up the name of the class being overloaded as its unique parameter. Nevertheless, things get interesting right now since the “__set()” method can be triggered by overloading a property access. The example below demonstrates this process:

// instantiate ‘CookieSaver’ object
$cookieSaver=&new CookieSaver();
// set cookie
$cookieSaver->setCookie();
// call __set() method and modify $this->expTimes['exp1'] array
element
@$cookieSaver->exp1=60;

As you can see, the previous example clearly shows how to overload a property access, which automatically triggers the “__set()” method that you learned before. With reference to this, please, take a look at the following line:

@$cookieSaver->exp1=60;

With this statement, what I’m doing is accessing the array element $this->expTimes[‘exp1’] and assigning to it a value of 60 seconds. Of course, here the “magic” happens because the “__set()” method is called automatically by the PHP interpreter, resulting in the following output:

Setting new cookie…with an expiration of 60 seconds.

Wasn’t that cool? Once the previous class has been overloaded, it’s possible to run custom code by a property access, as I demonstrated by the above example. Right, I have to admit that the “@” error suppression character isn’t very elegant, but this one-liner allowed me to run code behind the scenes, all without an explicit call to the “__set()” method.

Provided that you understood the previous example, see the following sample code, where the remaining elements of the $expTimes array are modified in turn:

// call __set() method and modify $this->expTimes['exp2'] array
element
@$cookieSaver->exp2=120;
// call __set() method and modify $this->expTimes['exp3'] array
element
@$cookieSaver->exp3=240;

After running the above script, the output I get on my browser is as follows:

Setting new cookie…with an expiration of 120 seconds.
Setting new cookie…with an expiration of 240 seconds.

At this stage, you saw how a class can be overloaded in PHP 4, in order to trigger the respective “__set()” method and run the code wrapped by it. Now, let’s move forward and see how the corresponding “__get()” method can be triggered when a property access is appropriately overloaded.

The next few lines of the article explain how to achieve this.

{mospagebreak title=Going deeper into property access overloading: using the “__get()” method}

Remember that I said it was also possible to trigger a “__get()” method when a property access is overloaded? Fine, because that is what I’d like to show you in this section of the tutorial.

In order to demonstrate how this process is performed, I’ll redefine the previous “CookieSaver” class, this time replacing its “__set()” method by a “__get()” method. This really sounds simple, so here’s the source code of the modified class:

// define ‘CookieSaver’ class and implement __get() method
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;
    }
    // get value of property via __get() method
    function __get($property){
        $expTime=$this->expTimes[$property];
        setcookie(‘newCookie’,urlencode(‘This cookie has been set
via the __get() method’),time()+$expTime);
        echo ‘Retrieving new cookie…with an expiration of
‘.$expTime.’ seconds.';
        return;
    }
}

As I illustrated above, now the “CookieSaver” class specifically implements a “__get()” method, instead of exposing the previous “__set()” method that you learned before. Also, notice that the definitions of the remaining methods are the same, which means obviously that the class sets and retrieves a simple cookie via its “setCookie()” and “getCookie()” methods respectively.

As you can see, now the “__get()” method has been defined in such a way that it retrieves a specific element of the $expTimes array and assigns this value to the expiry of the cookie in question. From this example, you’ll surely realize that the generic signature of a “__get()” method is the following:

__get($property){
    // method definition goes here
}

By this point, after the prior __”get()” method has been explicitly implemented, it’s time to see how it can be triggered, overloading a specific property access. The code snippet below shows the process that calls the “__get()” method, when a property access is performed:

// overload ‘CookieSaver’ class
overload(‘CookieSaver’);
// instantiate ‘CookieSaver’ object
$cookieSaver=&new CookieSaver();
// set cookie
$cookieSaver->setCookie();
// call __get() method and retrieve $this->expTimes['exp1'] array element
echo @$cookieSaver->exp1;

In the above example, the “CookieSaver” class is first overloaded by using the “overload()” function, and then the “__get()” method is triggered by the property accessing line listed below:

echo @$cookieSaver->exp1;

This statement executes the code defined inside of the “__get()” method, which results in the following output:

Retrieving new cookie…with an expiration of 900 seconds.

In a similar way, it’s perfectly feasible to access the remaining elements of the $expTimes array, like this:

// call __get() method and retrieve $this->expTimes['exp2'] array
element
echo @$cookieSaver->exp2;
// call __get() method and retrieve $this->expTimes['exp3'] array
element
echo $cookieSaver->exp3;

In both cases, the “__get()” method is automatically called and the output produced by the previous examples is the following:

Retrieving new cookie…with an expiration of 1800 seconds.
Retrieving new cookie…with an expiration of 3600 seconds.
 

As you’ll realize, the PHP parser automatically triggers the execution of the “__get()” method, if there’s a line of code that overloads a property access, just like the examples shown a few lines above.

At this stage, I hope that you already understand the logic that surrounds the overloading of classes in PHP 4. Even when the examples are just that, they show in a simple way how to execute custom code without having to explicitly call both “__set()” and “__get()” methods. Certainly, there’s plenty of room to experiment with this concept, and you’ll probably find more useful applications when overloading your PHP classes.

To wrap up

In this first part of the series, I explored the implementation of class overloading in PHP 4, specifically using the “overload()” function, which comes in handy for triggering “__set()” and  “__get()” methods, when a property access is overloaded.

However, we’re just beginning the journey. Over the next tutorial, I’ll explain how to combine the two “__set()” and “__get()” methods inside the same class, as well as how to trigger the “__call()” function via method call overloading. You don’t have any excuses to miss it! 

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort