Using Inheritance, Polymorphism and Serialization with PHP Classes

If you are working with classes in PHP, you will sooner or later encounter inheritance, polymorphism, and serialization. The ability to use these three will help speed up your code writing. This article covers how to use them, and more.

Introduction

Inheritance, in object oriented terms, allows us to create subclasses of a given class. Think of it as a hierarchy of different kinds of classification. For example, in our previous article we used a class called human. Humans come in different forms; you have Africans, Europeans, Asians, and so forth. They all have similar attributes, e.g. legs, arms, eyes, and so on, but are different in other ways. Now, to translate these similarities and differences into code, we would use inheritance. In addition to inheritance we are going to discuss both polymorphism and serialization, among other topics.

Inheritance

The syntax for creating an inherited class is:

Class new_class_name extends original_class_name{}

Let’s look at our human class. The class as it stands now is very broad. Say we  want to specify an African person with this class. This is what we will do:

class human{
function human($hcolor){
     $this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return  “This <b>”.get_class($this).”</b> has <b>” .$this-
>hcolor. “</b> hair,and <b>” .$this->legs. “</b> legs<br>” ;
}
}
class African extends human{
}
//instantiate the class
$jude = new human(“black”);
$jane = new african(“brown”);
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();

In the above code we added a new class (African) which inherited everything from the human class. And we created a instance of this new class called jane. This is what we get when we run this code:

As you can see from the result, the new class name (african) is now shown. There is virtually no difference between the African class and the human class. This is because the extends keyword is causing the new class to inherit everything from the human class. So, the African is in effect, at the moment, the same as human. So how do we make differences between the two? We do this by specifying, within the new African class, certain variations:

class human{
function human($hcolor){
       $this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return  “This <b>”.get_class($this).”</b> has <b>” .$this-
>hcolor. “</b> hair,and <b>” .$this->legs. “</b> legs<br>” ;
}
}
class African extends human{
var $hcolor=”black”;
function African() {}
}
//instantiate the class
$jude = new human(“black”);
$jane = new african();
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();

In the code above we added a variable called hcolor. We did this because the African class represents a new type of human. Now, we need to disable the constructor function human, because the African class inherits everything from the human class including its constructor function, so we need to create an equivalent function in the African class. So we add:

function African() {}
}

This effectively overwrites the  constructor function of the human class. Note that this function does not take any arguments.

As the results above show, the hair color for the African class is black. It will always be black no matter what we add to the jane object, because the hair color specified in the new African class is declared as black.

{mospagebreak title=Polymorphism}

The idea of polymorphism is that when we look at an object, and ask it to do something, like call one of its methods, we do not really need to know how a class works or exactly how it does its internal workings. We need to know how it works and what it does when we are defining the class and writing the methods, but we do not need to know, as programmers making use of the object, exactly how it all happens.

For instance, we can have two different objects with methods that have the same name, which will do similar things — but with a difference depending on the kind of object we call the method from. The principal of polymorphism states that we do not need to specify anything different when we ask the object to do whatever it is that we want it to do. To demonstrate, let’s  make some changes to our human class:

class human{
function human($hcolor){
       $this->hcolor=$hcolor;
}
function say_hello(){
echo “Hello!<br>”;
}
var $legs=2;
function report(){
return  “This <b>”.get_class($this).”</b> has <b>” .$this-
>hcolor. “</b> hair,and <b>” .$this->legs. “</b> legs<br>” ;
}
}
class African extends human{
var $hcolor=”black”;
function African() {}
}
//instantiate the class
$jude = new human(“black”);
$jane = new african();
$jude->legs++; //increase legs by one
echo $jane->say_hello();
echo $jude->say_hello();

If we want the African class to say something other than hello, here’s what we do:

class human{
function human($hcolor){
       $this->hcolor=$hcolor;
}
function say_hello(){
echo “Hello!<br>”;
}
var $legs=2;
function report(){
return  “This <b>”.get_class($this).”</b> has <b>” .$this-
>hcolor. “</b> hair,and <b>” .$this->legs. “</b> legs<br>” ;
}
}
class African extends human{
var $hcolor=”black”;
function African() {}
function say_hello(){
echo “Hello there!”
}
}
//instantiate the class
$jude = new human(“black”);
$jane = new african();
$jude->legs++; //increase legs by one
echo $jane->say_hello();
echo $jude->say_hello();

We asked both objects to say hello using exactly the same syntax and it worked as expected. This is important in object oriented programming because it allows the object to take control of the way it works. In other words, we can make the same request of two different objects, and based on the different workings of the two objects, we end up with two (possibly different) results. This makes coding cleaner and more intuitive.

{mospagebreak title=Class Functions Without Instances}

There is a way to use a class function without having to create an instance of a class. This capability has been added since PHP 4 and is useful if you only need a function from a class, but not the entire class itself. The syntax for doing this is:

the_Classname::the_Method();

To demonstrate, lets use the “say_hello()” function in our human class:

<?
class human{
function human($hcolor){
       $this->hcolor=$hcolor;
}
function say_hello(){
echo “Hello!<br>”;
}
}
echo “The result of the uninstantiated class function is: <br>”;
echo herehuman::say_hello();
?>

As you can see from the code above, all I did was add the human::say_hello() line of code. The say_hello() function is a function of the human class. Normally, to use this function we would have to create an instance of the class, but in this case we did not, so let’s run the code and see what happens:

The above screen shot shows the results of a class function used without instantiating the class.

Remember to include the class from which you want to use the method. Also, as a matter of good coding practice, you can make sure the specific function exists in a class before using it. You do this like so:

if(method_exist(the_classname::function_name())){
//do something here…
}

To check that the say_hello() function exists in our human class:

if(method_exist(human::say_hello())){
//do something here..
}

Destroying Objects

In most object oriented languages there is a built-in capability to free or destroy objects that you no longer want to use. Why do you need to destroy an object? Well, the reason is quite simple. The creation and use of an object is resource intensive, and it is therefore important to free up the resources that get tied up when using objects. This is done by calling the unset() function after you’ve instantiated the object:

$object = new Classname
unset($object);

Remember to call this function at the very end of a script to avoid destroying the object while it is needed by the program.

{mospagebreak title=Serializing}

Objects by their very nature are very difficult to manage as strings or numbers. This makes it difficult to store them in a database, pass along to a script, or use them generally for storing values, such as, for example, setting one as a cookie. To solve this problem, PHP has a function called serialize(). This function takes a variable and turns it into a more manageable version of itself. The syntax of this function is:

$var =serialize(object);

And to return the variable to its original state:

$object =unserialize($var);>

Both functions are a bit like encryption. If you want to hide a text you turn it into something unreadable, and then if you want to show the text you return it to its plain text state. This is more or less what serialization is about.

When using these functions make sure to include the class definitions on the page that you call unserialize().

Both functions look for two special functions when serializing objects:

serialize() checks to see whether your class has a function with the name  __sleep. If  that function is present, it  will be run prior to any serialization. It is responsible for cleaning up the object and then returning an array that includes the names of all variables of that object that should be serialized.

The purpose of the   __sleep function is to close any database connections that an object may have, commit pending data, or perform similar cleanup tasks. The function is useful for saving large objects.

unserialize() checks for the presence of a function with the name  __wakeup. If present, this function can reconstruct any resources that object may have.

The intended use of __wakeup is to re-establish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Conclusion

While coding with functions and objects makes programming easy, it can also slow down code execution, particularly on large projects. So take care when deciding to use it.

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

chat sex hikayeleri Ensest hikaye