Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

PHP Object Oriented Programming: An Overview Under the Language

In this article we will see all the concepts that involve OO programming in PHP, with some code examples explained and adapted to most recent versions.

Object-Oriented programming (OOP) was developed because limitations were present in earlier programming approaches i. e. procedural and structural programming.

Procedural language is just a set of instructions where each instruction tells the computer what to do: Get some input from user, add those numbers, multiply by four and display the output. So when these list of instructions increase, the programmer adopts functions. Each function has a clear purpose and a clearly defined interface to the other functions in program and that’s why procedural programming consists of functions. Dividing a program into functions and then combining those functions into a large entity called a module. Structural programming consists of both functions and modules.

So even making modules and functions in structural programming, the sign of strain exists because as the program grows complexity increases. There are two main reasons for this problem (complexity).

First is that function have unrestricted access to global data.

As we know, two types of data exist: one is Local data and the other is global data. Local data is accessible only within the function, while global data is accessible to the whole program. So when global data is required by more than one function, program complexity arises. Because the data needed by one function may be changed by another function in the program. In a large program, there are many functions and global data items and it will lead to even larger number of potential connections between data and functions.

Second is unrelated functions and data, which is basis for procedural programming and it provides a poor real world model.

Arrangement of separate data and functions in procedural programming does a poor job of modeling things in the real world. In physical world, we deal with objects such as balls and cars. These objects are not like data and not like functions. Also complex real world objects have both attributes and behavior.

Attributes: Attributes are characteristics of objects. For example for ball, color and size; and, for cars, model number and horsepower are attributes. So attributes in real world are equal to data in a program. They have a specific values, such as red (for ball color).

Behavior: Behavior is like a function: you call a function to do something and it does it. Same is the case with real life objects because they also do something in response to some stimulus. If you apply brakes in a car, in response the car will stop.

The object oriented approach

In OOP you have to combine both the data and function into a single entity called object. And the object’s functions provide the only way to access its data. If you want to read a data item in an object, you call a member function in the object. The member function in turn will access the data and return the value to you. So you can’t access the data directly. The data is hidden, and is safe from accidental alteration. Data and functions are said to be encapsulated into a single entity. Data hiding, Data encapsulation, inheritance and polymorphism are the main fundamental concepts of OOP.

Data Hiding

Data hiding means showing only those details to the outside world which are necessary for them and hiding all other details from them. For example an email server contains millions of email addresses and login information but it will allow only the owner of email account by providing his original credentials. So in OOP we have objects which have attributes and behaviors and they are hidden from outside classes and that’s the main reason we say that object-oriented programming follows the principle of information hiding. In OOP information hiding is “Hiding object details (attributes and behavior) from the users. ” Here by user we mean object of another class. Information hiding in OOP is obtained by using the following principles.

  • All information related to an object must be stored within the object.
  • It can only be manipulated by the object itself.
  • It must be hidden from outside world.
Encapsulation

Encapsulation means “we have enclosed all the details of the object within the object itself. ” Or we can say “The practice of separating the user from true inner workings of an application through well-known interfaces is known as encapsulation” Information hiding is obtained through encapsulation so they are much related concepts. As we know that characteristics of object are data and behavior. So we can say that data and behavior are tightly coupled inside the object and both the implementation details and structure information are hidden from outside world.

Figure 1. UML class diagram for Michel

From Figure1 you can see that Michel stores his attributes and behaviors in himself. So it is up to Michelto share this information with outside world or not. Same is the case with his behaviors. No other object in real life can use his behavior of talking without his permission.

So we can say that attributes and behavior of Michel are encapsulated in him. Any other object don’t know about these information of Michel unless he wants to share it with him through an interface.

Inheritance

A child inherits characteristics of parents. Besides inherited characteristics, a child may have its own unique characteristics. If a class B inherits from class A then it contains all the characteristics (information and behavior) of class A. The parent class is called base class while the child class is called derived class. Besides inherited characteristics, derived class may have its own unique characteristics.

Polymorphism

Polymorphism means different forms. For example both diamond and coal are different forms of carbon. In OO model, polymorphism means that different objects behave in different ways for the same message. For example we have a base class “shape” and three more classes are derived from it i. e. Line, circle and triangle. All the derived classes contain a method (behavior) called draw( ). Now calling the same method will have different results, depending upon the object type.

Up-to this point we have discussed common concepts of OOP, now let’s move to implementation of object-oriented concepts, including PHP specific examples.

Classes

A class is generalized definition of a thing and acts as a blueprint.

Syntax of class

Listing 1. General syntax of a class.

Class ClassName {
    function function_name(){
   // function code
}

Listing 1 shows syntax of a class. Basically a class begins with the keyword class and then after that follows class name. After that class definition is placed within curly braces:

Class ClassName {
}

A class definition consists of variables (attributes) and functions (behaviors). So in Listing 1 we have defined a function only. Defining a function in class is same as defining it outside the class i. e. it starts with keyword function then after that with function name:

function function_name(){
//function code. 
}

Defining variables (attributes) within classes are a little different from defining it outside of classes. A keyword (public, private, protected) must be added before each variable for its visibility purpose. We will discuss these terms in our next topic Field scope. Let’s see an example how to make a class.

Listing 2. How to create a class in PHP.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php
class math{
          function add(){
          echo"this is add method";}
          function sub(){
               echo"this is subtract method";}
                }
?>
<body>
</body>
</html>

In Listing 2 we have created a class math and inside this class we made two functions namely Add( ) and sub( ). Now if you run this program, your browser will show you empty window and nothing will be displayed. Why? The answer is that we haven’t created any object of class math, and we know that a class act as a blue print and is not loaded into memory until we create class objects. So let’s introduce the concept of creating objects and then we will create objects for the same class of Listing 2.

Objects

Object is an instantiations of a user defined class. Once you create a class you can create as many objects as you want. Syntax Creating an object in PHP is an easy task once you created a class. For creating an object you have to use a keyword “new” i. e.

$object=new classname( ); 

Declaring this statement will create an object of type class. Now to access a method of class through this object the syntax is: $object->function_name( );. If the function takes arguments you can also send argument to function. Now let’s create objects of class math declared in Listing 2.

Listing 3. Creating objects of class math.

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>class&objects</title>
</head>
<?php
class math{
          function add(){
          echo"this is add method<br>";}
          function sub(){
                echo"this is subtract method";}
                }
                $obj1=new math();
                $obj1->add();
                $obj2=new math();
                $obj2->sub();
?>
<body>
</body>   
</html>

Listing 3 is similar to Listing 2, only we have created objects i. e.

  • $obj1=new math(); //will create 1st object of class type.
  • $obj1->add();//will call function add( )in class math.
  • $obj2=new math();//will create 2nd objet of class type.
  • $obj2->sub();//will call method sub( ) in class math.

So running the code in Listing 3 will show the message declared in both the functions.

Figure 2. Functions are called through object.

Note: if you want to delete the object created you can use the unset( ) function and by writing object name in argument. For example unset($obj1) will delete $obj1.

Lets add this function to Listing 3 and check it.

Listing 4. Deleting objects.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>class&objects</title>
</head>
<?php
class math{
          function add(){
          echo"this is add method<br>";}
          function sub(){
                echo"this is subtract method";}
                }
                $obj1=new math();
                $obj1->add();
                $obj2=new math();
                $obj2->sub();
                unset($obj2);
                $obj2->add(); 
?>
<body>
</body>
</html>

Listing 4 is similar to Listing 3, only we have added:

unset($obj2);//this will delete the obj2. 
$obj2->add();//again calling method add( ) with obj2. 

The unset( ) function will delete the object and now calling again a method within class with that object will show an error like this as shown in Figure 3.

Figure 3. Shows error message after calling a method with deleted object.

Fields

Fields are attributes which are used to describe class characteristics. Or you can say declaring a variable inside a class is a field and the only difference from a normal variable in PHP is that they are prefaced with scope descriptors i. e. public, private, and protected.

Syntax

Listing 5: Syntax for declaring fields.

 Class classname{
Public $variable1=”Hello”; //notice the keyword public. 
Private $variable2=40;//notice the keyword private. 
}

In Listing 5 we have declared two fields with scope descriptors public and private.

Now if you want to invoke a field use the following syntax:

$object->variable1;

Here notice the ->operator sign and only variable name is used without $ sign.

Scopes of fields


Public

If we declare a variable through public scope in a class, it will be accessible by any object in the class and in this way it will spoil the concept Data hiding in OOP. So basically programmers avoid it and they only allow access to field through Public Methods.

So fields which are declared publically will be accessible within the class and to subclasses directly and from outside the class through objects.

Private

If we declare a field private, it will only be accessible within the class and no object will access it directly from outside the class. Also such field can be accessed through objects of class which will make their way to such field through public function within the class, as they are accessible only within the class .

Protected

If we declare a field protected, it will be accessible by the class and its sub classes. So any attempt made by object to access a protected field will cause an error.

Scope of member functions

Like fields scope descriptors also exists for member functions within classes. Syntax of member function is:

Listing 6. Syntax of member function

Class classname{
Scope member_function_name( )// use public, protected or private instead of scope keyword
{
//function codes goes here;
           }
}

Public

Public functions can be accessed from anywhere in the program.

Private

Private functions can be accessed only within the class and can’t be accessed by any subclass or objects.

Protected

Protected functions can be accessed within the class and classes inherited from that class and not by objects.

$this variable in PHP

We have discussed rules for defining field within a class. Now if you want to access value of a field/variable within the class i. e. inside of member function of class, you should use a special variable $this.

Syntax

$this->variable_name;

Rather than over-explaining this concept let us go to Listing 7 to understand the concept of $this variable and scope of fields and functions.

Listing 7. Example to show usage of $this, scope of field and functions.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>use_of_scope</title>
</head>
<body>
<?php
class math{
     # this program will show scope of variables and functions;
     public $var1=22;
     private $var2=10;
     protected $var3=20;
     public function add(){
     $sum=$this->var1+$this->var2;
     echo "<b>sum of var1 & var2 is = </b>". $sum. "<br>";
     $total_sum=$sum+$this->var3;
  echo "<b>total sum of var1,var2 & var3 is =</b>". $total_sum. "<br>";    
          }
          protected function sub(){
          $sub=$this->var1-$this->var2;
     echo"<b> subtraction of var2 from var1 is =</b>". $sub. "<br>";
                }
                private function div(){
                $div=$this->var3 / $this->var2;
echo"<b> dividing var3 by var2 is equal to =</b>". $div. "<br>";
                     }
          
         }
          class check extends math{
                public $var4=10;
                public function call(){
                          
     echo "<b> output of var4 is=</b>". $this->var4 . "<br>";   
     echo "<b> output of var1 is=</b>". $this->var1 . "<br>";   
//echo $this->var2; // will show error as $var2 is private in             //parent class. 
echo "<b> output of var3 is=</b>". $this->var3 . "<br>";         
echo"<b>Add function is called from child class</b><br>";
echo  $this->add();
echo"<b> Sub function is called from child class</b><br>";
echo $this->sub();
//echo "Output of div function can't be called as it's private: <br> " $this->div();
                                          }
                }
     
     $obj1=new math();
     $obj1->add(); 
     //$obj1->sub(); //can't be called as sub() is protected; 
     //$obj1->div();  //can't be called as div() is private;
     $obj2=new check();
     $obj2->call();
echo"<b> output of var1 through object of child class=</b>". $obj2->var1; //accessible through object of child class;
     
?>
</body>
</html> 

In Listing 7 we have declared three variables with scope descriptors public, private and protected respectively in class math. Also three member functions with scope descriptors public, protected and private are declared with math class.

Watching clearly the code, you will see that there is another class check created which is derived from math class. Within check class we also created another function call( ). Also we created two objects($obj1 & $obj2) one for math class and another for check class.

By clearly examining the code you will see slashes (//)which are used for commenting the code. Now run the exact code in Listing 7 you will see the output as shown in Figure 4.

After that remove the slashes (//) one by one and run the code you will see various error messages related to scopes.

Rest of code is simple and comments are present for understanding purpose.

Figure 4. Output of Listing 7 which shows result of scope of variable and functions.

Constructors

Constructors are used for automatic initialization. So a constructor is a member function that is automatically called whenever an object is created.

When a function exists with the same name as that of class is called constructor. A constructor can’t return a value but only a value can be passed to it.

In PHP 4 and PHP 5, class constructor is written as:

Listing 8. Syntax for constructors.

    
Class math{
    function math($value){
}
}

Also in PHP 5 a constructor can also be written as:

Listing 9. Syntax for constructor in PHP5

function __construct($value)
{
}

Listing 10. Program for making constructors,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>constructor</title>
</head>
<body>
<?php 
class person{
     var $name;
     function __construct()
     {
          $name='Mr-bool';
          echo"constructor is called when object was created <br>";
          echo "Name is ". $name. "<br>";
          
     }
     function get_name($person_name){
     $this->name=$person_name; 
      echo"Name is ". $this->name;}
     }
     $obj=new person();// constructor is called automatically;
     
     $obj->get_name("Diogosouzac");
     
?>
</body>
</html>

In Listing 10 we have made a constructor in which we assigned a name to variable $name by default. And another member function get_name($person_name) is declared which will accept an argument and will print it.

By creating object $obj, the constructor will be called automatically and will print the value whatever by default is present there. Also using $obj we also passed a name to get_name( ) as an argument. The complete output of code is shown in Figure 5.

Figure 5: Constructor is called automatically upon creation of object as shown in figure.

Destructors

As we know that constructor is called when an object is created. So you may be wondering that there should be a function which should be called automatically when an object be destroyed. Such a function is destructor.

Syntax

Listing 11. Syntax of destructor

Class classname{
function __destruct(){
}}

Difference between constructor and destructors is that destructors can’t take any argument. To understand how destructors work lets add destructor Listing 12.

Listing 12. How destructors are called when object was deleted.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>constructor</title>
</head>
<body>
<?php 
class person{
     var $name;
     function __construct()
     {
          $name='Mr-bool';
          echo"constructor is called when object was created <br>";
          echo "Name is ". $name. "<br>";
          
     }
     function get_name($person_name){
     $this->name=$person_name; 
      echo"Name is ". $this->name. "<br>";}
      function __destruct(){
       echo"Object destroyed";}
     }
     $obj=new person();// constructor is called automatically;
     
     $obj->get_name("Diogosouzac");
     unset($obj);
     
?>
</body>
</html>

Listing 12 is similar to Listing 10 the only difference is that we have added destructor function which will be called automatically by destroying object.

So here we have deleted object $obj through unset( ) and destructor is called automatically as shown in Figure 6.

Figure 6. Destructor is called when object was destroyed.

Use of scope resolution operator

Scope resolution is combination of two colons (::) and is used for specifying of data to which class it belongs. Also you can call a member function directly if it is not declared protected or private i. e.

classname::method_name(). 

It is also helpful in invoking of a parent constructor within a child constructor. To understand this concept, let’s write a program.

Listing 13. Working of scope resolution operator.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>invoking_parent_constructor</title>
</head>
<body>
<?php 
class subject{
     var $subject;
     function __construct(){
     echo"your favorite subject is mathematics<br>";}}
          
     class teacher extends subject{
          function __construct(){
          echo"your teacher favorite subject is English<br>";
          echo"while<br>";
          parent::__construct();
                     }
          }
          $obj=new teacher();
                     ?>
</body>
</html>

Listing 13 introduces two classes subject (the parent class) and teacher (the child class). Both classes have their own constructors and we have created object for only child class ($obj).

Figure 7. Invoking of parent constructor through scope resolution operator.

Overriding

As we know that a child class may have its own constructor which will be used instead of parent constructor. So we can also use the same concept for other member functions of class, and is called overriding.

To obtain it in PHP we declare member function in child classes with the same signature (same name and same number of arguments) as that of parent class. Let’s write a program to understand the concept of overriding in PHP.

Listing 14. Overriding

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 0 Transitional//EN" "http://www. w3. org/TR/xhtml1/DTD/xhtml1-transitional. dtd">
<html xmlns="http://www. w3. org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>overriding</title>
</head>
<body>
<?php 
class student{
     var $name;
     function __construct($student_name){
          $this->name=$student_name;
          echo"Name of student is=". $this->name. "<br>";}
          function favourite_subjects(){
          echo$this->name. " favourite subject is Maths<br>";}
                }
class games extends student{
     function __construct(){
     echo"favourite game of almost all students in pakistan is cricket<br>";}
          
          function favourite_subjects(){
          echo"Students who play cricket doesn't like science subjects<br>";
                }
}
                $obj1=new student("zohaib");
                $obj1->favourite_subjects();
                $obj2=new games();
                $obj2->favourite_subjects();
                
?>
</body>
</html> 

In Listing 14 we created two classes i. e. student and games. Within both classes a member function favourite_subjects() exists but the same function executes a different piece of code in both classes. Now as we create an object for a class, constructor of that class is automatically called. Two objects are created $obj1 & $obj2 one for each class. So when we call function which exists in both classes which one is called? Here is the rule: objects of base class doesn’t know anything about derived class function and will always execute base class functions. Depending upon the object:

  • $obj1->favourite_subjects( );//being object of student class it will execute the function in its own class
  • $obj2->favourite_subjects( );// being object of games class it will execute the function in its own class.

Figure 8. Depending upon the type of object member functions are called.

Conclusion

We have touched the basics of OOP and remember the best way to learn is to practice the code and understand it. Learning OOP in PHP will help you in learning Object oriented programming for any OO language. You will feel comfortable with PHP projects after learning it.

Practice and learn this in our next tutorial we will learn advance OOP in PHP plus with a practical example of how to make our code modular for complex projects using OOP.



Software developer doing B.E in Computer Science at Hamdard university karachi. Have good skills in php, html, javascript and css.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login