Object Oriented Programming Concepts in PHP

Introduction

In this article we learn the basic concepts of Object Oriented Programming in PHP. This article covers Object Oriented Programming conecepts that are used in PHP. This articles covers the following topics.

  • Class
  • Create variables for a class
  • Create function for a class
  • Class constructor
  • Instantiate a class
  • creating class constructor
  • Variable and method call using objects
  • Constructor and Destructor
  • visibility
  • Object Inheritance
  • Scope Resolution Operator
  • Overloading
  •  Late static Binding

Class

A Class is a template; a template for an Object. Let's understand this by an example, you have seen many times Humans, a shop, a house, a ground, a shirt, t-shirts and many more things. These are all examples of classes. Let's understand how they become an object. Suppose a human is class then Rajeev is an object of that class as in the following:

oopsDef

Ground: cricket ground , hockey ground, football ground, and so on.
Animal: cow, dog, elephants ...

The following is an examle of creating a class in PHP:

  1. class <className>{  
  2. // define member variables  
  3. // define methods  
  4. }   
To create a class in PHP we should use the class keyword and then a <className>. This className is the programmer's choice depending on their needs, and opening and closing braces.

Create variables for a class

A class variable is known as properties, these variables can store values and these values are important information for your class. So we can say that class variables are class properties.

Example
  1. class student{  
  2. var $rollNo;  
  3. var $name;  
  4. var $address;  
  5. }  
In this code above, $rollNo, $name and $address are the class variables.

Note:  When you are declare any class variable you should always use the "var" keyword in PHP.

Create Methods for class

Class methods or functions are like regular functions, the only difference is they are inside the class. In simple words class functions are known as, or called, "Methods". These methods are used for retrieving the data or manipulating the data. In the following example I am trying to demonstrate the class methods.
  1. class student{  
  2. var $rollNo;  
  3. var $name;  
  4. var $address;  
  5. function Display(){  
  6. // codes   
  7. // statement  
  8. }  
  9. function AddStudent(){  
  10. // codes for adding records   
  11. }  
  12. }// end of class  
Instantiate a class


Let's understand the meaning of "instantiation". In general programming words , " The process of creating an Object is known as as instantiation". The new keyword is used to create an object of that class. The new keyword and the name of the class to instantiate from. Let's see the syntax and an example.

Syntax

$objName = new className();

Example


$ObjStudentName = new student();

Creating a class constructor


Let's understand what a constructor is before trying to understand the creation process. Suppose you want an object to have some value (certain) when you instantiate that object. If you want records of student to be initialized after the object creation then that is what the class constructor is used for. The __construct() function calls the constructor in PHP.

Syntax

void __construct( [ mixed $args = "" [ , $ . . . ] ] )

Example
  1. class student{  
  2. var $rollNo;  
  3. var $name;  
  4. var $address;  
  5. function __construct(){  
  6. $this->$rollNo=101;  
  7. $this->$name='rajeev';  
  8. $this->$address='pune';  
  9. }  
  10. }// end of class  
Variable and method call using objects

In this topic we will see how we reference the class variable and methods in PHP.

Syntax

$object -> variable;
$object -> function();

Example

$ObjStud -> name;
$ObjStud -> AddStudent();

  1. <?php  
  2. class student{  
  3. var $rollNo;  
  4. var $name;  
  5. var $address;  
  6.         function display($rNo$Nam$Add){  
  7.         $rollNo=$rNo;  
  8.         $name=$Nam;  
  9.         $address=$Add;  
  10.         echo "Roll No -" .$rollNo"<br/>";  
  11.         echo "Name - " .$name"<br/>";  
  12.         echo "Address - " .$address"<br/>";  
  13.     }  
  14.         function __construct($rNo$Nam$Add){  
  15.             $rollNo=$rNo;  
  16.             $name=$Nam;  
  17.             $address=$Add;  
  18.             echo "Constructor is called <br/>";     
  19.             echo "Roll No -" .$rollNo"<br/>";  
  20.             echo "Name - " .$name"<br/>";  
  21.             echo "Address - " .$address"<br/>";  
  22.          
  23.     }  
  24. }  
  25. $ObjStud = new student("101","rajeev","New Delhi");  
  26. echo "-------------------------------<br/>";  
  27. $ObjStud->display("102","ranjan","New Delhi");  
  28. ?>  

OOPSINPHP
Constructor and Destructor

A constructor is a function that is executed after the object has been initialized. Initialized means its memory allocation, instance, properties and so on. Its purpose is to put the object in a valid state. Usually, an object is always in a usable state, requiring some data. The purpose of the constructor is to force this data to be given to the object at instantiation time and disallow any instances without such data.

The __construct() method is used for the constructor.

Let us consider a simple class that encapsulates a string and has a method that returns the length of this string.

  1. <?php  
  2. class constructorTest{  
  3.     private $str;  
  4.     public function strString($str){  
  5.         $this->str= (string) $str;  
  6.     }  
  7.     public function getLength(){  
  8.     if($this->str===null){  
  9.         throw new RuntimeException(" Invalid state");  
  10.     }  
  11.     return strlen($this->str);  
  12.     }  
  13. }  
  14. ?>  

In order to be a valid state of code, this function requires setString to be called before getLength. This can only happen using the constructor.

  1. class constructorTest{  
  2.     private $str;  
  3.     public function __construct($str){  
  4.         $this->str- (string) $str;  
  5.     }  
  6.     public function getLength(){  
  7.         return strlen($this->str);  
  8.     }  
  9. }  

A Destructor is called when an object is about to be freed from memory. In general words a destructor has cleanup code to destroy the object instance. PHP cleans all the resources held by the script when the script execution ends.

The __destructor() method is used to destroy the free resources, like files, databases and so on.

Visibility

Visibility in PHP determines how your class members can be accessed. There are mainly the 3 types of visibility access in PHP, they are public, private and protected.
  • Private Member: Can only be accessed from inside the class itself.
  • Protected Member: Can only be accessed from inside the class itself and its child classes.
  • Public Member: Can be accessed from anywhere, outside, inside, in a child class, everywhere.
Object Inheritance

Inheritance is the ability to derive new classes from existing classes. A derived class (or sub class) inherits the instance variables and methods of the base class (or superclass) and they (may) add new instance variables and methods. New methods may be defined with the same name as those in the base class; this process, known as overriding. extends the keyword to the use of inheriting the base class. In the following example we demonstrate the concepts of Inheritance with a simple example.  
  1.  <?php  
  2. class A  
  3. {  
  4.     public $public = 'Public Access Modifier';  
  5.     protected $protected = 'Protected Access Modifier';  
  6.     private $private = 'Private Access Modifier';  
  7.    
  8.     function printHello()  
  9.     {  
  10.         echo $this->public;  
  11.         echo $this->protected;  
  12.         echo $this->private;  
  13.     }  
  14. }  
  15.    
  16. $obj = new A();  
  17. echo $obj->public// Works  
  18. echo $obj->protected// Fatal Error  
  19. echo $obj->private// Fatal Error  
  20. $obj->printHello(); // Shows Public, Protected and Private  
  21.    
  22. class B extends A  
  23. {  
  24.     // We can redeclare the public and protected method, but not private  
  25.     protected $protected = 'Protected2 Access Modifier';  
  26.    
  27.     function printHello()  
  28.     {  
  29.         echo $this->public;  
  30.         echo $this->protected;  
  31.         echo $this->private;  
  32.     }  
  33. }  
  34.    
  35. $obj2 = new B();  
  36. echo $obj2->public// Works  
  37. echo $obj2->protected// Fatal Error  
  38. echo $obj2->private// Undefined  
  39. $obj2->printHello(); // Shows Public, Protected2, Undefined  
  40. ?>  

Scope Resolution Operator

The Scope resolution operator (::) defines a function outside a class or when we want to use a global variable but also have a local variable with the same name. Scope Resolution Operator (::) is a token that allows access to static, constant and overridden properties or methods of a class. When we reference these items from the class definition, use the name of the class.

Overloading

PHP's overloading is different than other Object Oriented languages. Overloading provides the ability to have multiple methods with the same name but various quantities and types of arguments and their return types. In PHP, however, overloading allows the dynamic creation of properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope.

Property Overloading
  • public void __set( string $name, mixed $value ): Run when writing data to inaccessible properties.
  • public mixed __get ( string $name): Reading data from inaccessible properties.
  • public bool __isset( string $name ): Is triggered by calling isset() or empty() on inaccessible properties.
  • public void __unset( string $name): This function is invoked when unset() is used on inaccessible properties.
  1. <?php  
  2. class PropertyTest  
  3. {  
  4.     private $data = array();  
  5.     public $declared = 1;  
  6.     private $hidden = 2;  
  7.                   
  8.     public function __set($name$value)  
  9.     {  
  10.         echo "Setting '$name' to '$value'\n";  
  11.         $this->data[$name] = $value;  
  12.     }  
  13.    
  14.     public function __get($name)  
  15.     {  
  16.         echo "Getting '$name'\n";  
  17.         if (array_key_exists($name$this->data)) {  
  18.             return $this->data[$name];  
  19.         }  
  20.       }  
  21.    
  22.     public function __isset($name)  
  23.     {  
  24.         echo "Is '$name' set?\n";  
  25.         return isset($this->data[$name]);  
  26.     }  
  27.    
  28.     public function __unset($name)  
  29.     {  
  30.         echo "Unsetting '$name'\n";  
  31.         unset($this->data[$name]);  
  32.     }  
  33.     public function getHidden()  
  34.     {  
  35.         return $this->hidden;  
  36.     }  
  37. }  
  38.    
  39. $obj = new PropertyTest;  
  40. $obj->x = 1;  
  41. echo $obj->x . "\n\n";  
  42. var_dump(isset($obj->x));  
  43. unset($obj->x);  
  44. var_dump(isset($obj->x));  
  45. echo "\n";  
  46. echo $obj->declared . "\n\n";  
  47. echo "This is the hidden field property:\n";  
  48. echo "Privates are visible inside the class, so __get() not used...\n";  
  49. echo $obj->getHidden() . "\n";  
  50. echo "Privates not visible outside of class, so __get() is used...\n";  
  51. echo $obj->hidden . "\n";  
  52. ?>  

OverloadingProperty

Late static Binding

Late static binding is a variant of binding somewhere between static and dynamic binding. Let us consider the following example:

  1. class A {  
  2. static $word = "hello world";  
  3. static function hello(){  
  4. print self :: $word;  
  5. }  
  6. class B extends A {  
  7. static $word ="good byee";  
  8. }  
  9. B :: hello();  
In this example, the PHP interpreter binds the function hello() to class A so the call to B :: hello() gives the output " hello world". If the self :: $word had been based on late static binding, then the result would be " good byee".

Summary
 

In this article we learned Object Oriented Programming concepts in PHP, we learned how to make a class in PHP, what the benefits of constructors and destructors are and all other object oriented topics we covered.

Next Recommended Readings