Object Oriented Programming

Introduction

Object-oriented programming is an approach of programming where objects and classes are used. Now-a-days Java and C++ are mostly used for object-oriented programming. There was limited scope of object oriented programming in PHP 4, but in PHP 5, the object model was rewritten for better performance and more features. Now PHP 5 has a full object model.

Table of contents

Object, classes

PHP : Creating classes and Instantiation

Setting Properties

Setting Methods

PHP : Scope Resolution Operator (::)

PHP : Class Constants

Understanding public, private, protected properties

Understanding public, private, protected methods

PHP : Constructor methods

PHP : Destructors methods

PHP : Using multiple instances of the same class

PHP : spl_autoload_register()

PHP : Inheritance

PHP : Interfaces

PHP : Object Cloning

PHP : Magic methods
 

What is an object ?

The fundamental idea behind an object-oriented language is to enclose bundle of variables and functions into a single unit and keep both variables and functions safe from outside interference and misuse. Such a unit is called object which acts on data. The mechanism that binds together data and functions are called encapsulation. This feature makes it easy to reuse code in various projects. The functions declared in an object provides the way to access the data. The functions of an object are called methods and all the methods of an object have access to variables called properties.
Following picture shows the components of an object.

components of an object

Class

In object-oriented programming, a class is a construct or prototype from which objects are created. A class defines constituent members which enable class instances to have state and behavior. Data field members enable a class object to maintain state and methods enable a class object's behavior. Following picture shows the components of a class.

concept of a php class

PHP : Creating classes and Instantiation

  • The class definition starts with the keyword class followed by a class name, then followed by a set of curly braces ({}) which enclose constants, variables (called "properties"), and functions (called "methods") belonging to the class.
  • A valid class name (excluding the reserved words) starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • Class names usually begin with an uppercase letter to distinguish them from other identifiers.
  • An instance is an object that has been created from an existing class.
  • Creating an object from an existing class is called instantiating the object.
  • To create an object out of a class, the new keyword must be used.
  • Classes should be defined prior to instantiation.

Example :

<?php  
  1. class Myclass  
  2. {        
  3.  // Add property statements here  
  4.  // Add the methods here  
  5. }   
  6. ?>  

In the following example keyword new is used to instantiate an object. Here $myobj represents an object of the class Myclass.

<?php      
  1. $myobj = new MyClass;   
  2. ?>  

Let see the contents of the class Myclass using var_dump() function (display structured information (type and value) about one or more variables) :

<?php      
  1. class Myclass  
  2. {        
  3.  // Add property statements here  
  4.  // Add the methods here  
  5. }  
  6. $myobj = new MyClass;  
  7. var_dump($myobj);  
  8. ?>  

Output :
object(Myclass)#1 (0) { }

Setting Properties

  • Class member variables are called properties. Sometimes they are referred as attributes or fields.
  • The properties holds specific data and related with the class in which it has been defined.
  • Declaring a property in a class is a easy task, use one of the keyword public, protected, or private followed by a normal variable declaration. If declared using var (compatibility with PHP 4), the property will be defined as public.
    • public : The property can be accessed from outside the class, either by the script or from another class
    • private : No access is granted from outside the class, either by the script or from another class.
    • protected : No access is granted from outside the class except from a class that’s a child of the class with the protected property or method.
  • nowdocs ( as of PHP 5.3.0) can be used in any static data context, including property declarations.

Example :

After an object is instantiated, you can access the property of a class using the object and -> operator. Any member declared with keyword "private" or "protected" cannot be accessed outside the method of the class.

<?php     
  1. class Myclass  
  2. {  
  3.  public $font_size =10;  
  4. }  
  5. $f = new MyClass;  
  6. echo $f->font_size;  
  7. ?>  

Output :
10

Note : There is a common mistake to use more than one dollar sign when accessing variables. In the above example there will be no $ sign before font_size (echo $f->font_size).

After defining methods we will discuss an example with public, private and protected class properties.

Setting Methods

  • The functions which are declared in a class are called methods.
  • A class method is exactly similar to PHP functions.
  • Declaring a method in a class is a easy task, use one of the keyword public, protected, or private followed by a method name.
    • public : The method can be accessed from outside the class.
    • private : No access is granted from outside the class.
    • protected : No access is granted from outside the class except from a class that’s a child of the class with the protected property or method.
  • A valid method name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • The method body enclosed within a pair of braces which contains codes. The opening curly brace ( { ) indicates the beginning of the method code and the closing curly ( } ) brace indicates the termination of the method.
  • If the method is not defined by public, protected, or private then default is public.
  • Can access properties and methods of the current instance using $this (Format $this->property) for non static property.

Example :

After an object is instantiated, you can access the method of a class using the object and -> operator. In the following example customize_print() method will print a string with a specific fontsize and color within a html paragraph element with the help of php echo statement.

<?php     
  1. class Myclass  
  2. {  
  3.  public $font_size ="18px";  
  4.  public $font_color = "blue";  
  5.  public $string_name = "w3resource";  
  6.  public function customize_print()  
  7.  {  
  8.  echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_name."</p>";  
  9.  }  
  10. }  
  11. $f = new MyClass;  
  12. echo $f->customize_print();  
  13. ?>  

 

 

Output :

Now change the value of font_size, font_color and the string and check what the method custimize_print() returns.

<?php     
  1. class Myclass  
  2. {  
  3.  public $font_size ="18px";  
  4.  public $font_color = "blue";  
  5.  public $string_name = "w3resource";  
  6.  public function customize_print()  
  7.  {  
  8.  echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_name."</p>";  
  9.  }  
  10. }  
  11. $f = new MyClass;  
  12. $f->font_size = "20px";  
  13. $f->font_color = "red";  
  14. $f->string_name = "Object Oriented Programming";  
  15. echo $f->customize_print();  
  16. ?>  

Output :
method red string

PHP : Scope Resolution Operator (::)

In PHP, the scope resolution operator is also called Paamayim Nekudotayim which means "double colon" or "double dot twice" in Hebrew. The double colon (::), is a token which allows access to static, constant, and overridden properties or methods of a class.

PHP : Class Constants

  • A special entity that remains fixed on an individual class basis.
  • Constant names are not preceded by a dollar sign ($) like a normal variable declaration.
  • Interfaces may also include constants.
  • When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable.
  • As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

Define and using a constant

<?php  
  1.   class MyClass  
  2.   {  
  3.   const constant1 = 'PHP Class Constant';  
  4.   function PrintConstant()   
  5.   {  
  6.   echo  self::constant1 . "<br>";  
  7.   }  
  8.   }  
  9.   echo MyClass::constant1 . "<br>";  
  10.   $classname = "MyClass";  
  11.   echo $classname::constant1 . "<br>"// As of PHP 5.3.0  
  12.   $class = new MyClass();  
  13.   $class->PrintConstant();  
  14.   echo $class::constant1."<br>"// As of PHP 5.3.0  
  15.  ?>  

Understanding public, private, protected properties

Properties can be public, private or protected. Public means that properties can be accessed everywhere, private means properties can be accessed by the class that defines the member and protected means properties can be accessed only within the class itself and by inherited and parent classes.

Example :

<?php  
  1. // Define a class  
  2. class Myclass  
  3. {  
  4.  // Declare $font_size as Public property  
  5.  public $font_size ="18px";   
  6.  // Declare $font_color as Private property  
  7.  private $font_color = "blue";   
  8.  // Declare $string_name as Protected property  
  9.  protected $string_name = "w3resource";   
  10.  // Declare a method to print properties value. This is public.  
  11.  function property_print()  
  12.  {  
  13.  echo $this->font_size;  
  14.  echo $this->font_color;  
  15.  echo $this->string_name;  
  16.  }  
  17. }  
  18. $obj = new MyClass;  
  19. echo $obj->font_size; //Display 18px   
  20. echo $obj->font_color; //Fatal error: Cannot access private property Myclass::$font_color in F:\wamp\..  
  21. echo $obj->string_name; //Fatal error: Cannot access protected property Myclass::$string_name in F:\wamp\..   
  22. $obj->property_print(); //Display 18pxbluew3resource  
  23. ?>  

Understanding public, private, protected methods

Methods can be public, private or protected. Public means that methods can be accessed everywhere, private means methods can be accessed by the class that defines the member and protected means methods can be accessed only within the class itself and by inherited and parent classes.

<?php  
  1. // Define a class  
  2. class Myclass  
  3.  {  
  4.  // Declare a public method<br> public function my_public_method()  
  5.  {  
  6.  echo "This is a Public method";   
  7.  }   
  8.  private function my_private_method()  
  9.  {  
  10.  echo "This is a Private method";   
  11.  }  
  12.  protected function my_protected_method()  
  13.  {  
  14.  echo "This is a Protected method";   
  15.  }   
  16.  // This is public  
  17.  function test()  
  18.  {  
  19.  $this->my_public_method();  
  20.  $this->my_private_method();  
  21.  $this->my_protected_method();  
  22.  }  
  23.  }  
  24.  $obj = new MyClass;  
  25.  $obj->my_public_method(); //Display This is a Public method  
  26.  $obj->my_private_method();//Fatal error: Call to private method Myclass::my_private_method() from context '' in F:\wamp\www..  
  27.  $obj>my_protected_method();//Fatal error: Call to undefined function my_protected_method() in F:\wamp\www..  
  28.  $obj->test(); //Display This is a Public methodThis is a Private methodThis is a Protected method  
  29. ?>  

Note : PHP uses inheritance in it's object model and when you extend a class, the subclass inherits all of the public and protected methods from the parent class. When we will discuss the inheritance, you will get more information about protected properties and methods.

PHP Constructor methods

  • The constructor is a special built-in method, added with PHP 5, allows developers to declare for classes.
  • Constructors allow to initialize object properties ( i.e. the values of properties) when a object is created.
  • Classes which have a constructor method execute automatically when an object is created.
  • The 'construct' method starts with two underscores (__).
  • Constructor is not required if you don't want to pass any property values or perform any actions when the object is created.
  • PHP only ever calls one constructor.

The general syntax for constructor declaration follows :

function __construct([argument1, argument2, ..., argumentN])
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.

Example :

<?php  
  1. // Define a class  
  2.  class Myclass  
  3.  {  
  4. // Declaring three private varaibles  
  5.  private $font_size;  
  6.  private $font_color;  
  7.  private $string_value;  
  8. // Declarte construct method which accepts three parameters  
  9.  function __construct($font_size,$font_color,$string_value)  
  10.  {  
  11.  $this->font_size = $font_size;  
  12.  $this->font_color = $font_color;  
  13.  $this->string_value = $string_value;  
  14.  }  
  15. // Declare a method for customize print   
  16.  function customize_print()  
  17.  {  
  18.  echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";  
  19.  }   
  20.  }  
  21. // Create a new object and passes three parameters  
  22.  $f = new MyClass('20px','red','Object Oriented Programming');  
  23. // Call the method to display the string  
  24.  echo $f->customize_print();  
  25.  ?>  

Output :
method red string

More example on constructors :

Like properties, constructors can call class methods or other functions. In the following example there is no need to call the method separately (after creating the object and passing the parameters, see the previous example) as it is already declared within the constructor. See the following example :

<?php  
  1. // Define a class  
  2.  class Myclass  
  3.  {  
  4. // Declaring three private variables  
  5.  private $font_size;  
  6.  private $font_color;  
  7.  private $string_value;  
  8. // Declarte construct method which accepts three parameters and the method customize_print()  
  9.  function __construct($font_size,$font_color,$string_value)  
  10.  {  
  11.  $this->font_size = $font_size;  
  12.  $this->font_color = $font_color;  
  13.  $this->string_value = $string_value;  
  14.  $this->customize_print();  
  15.  }  
  16. // Declare a method for customize print   
  17.  function customize_print()  
  18.  {  
  19.  echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";  
  20.  }   
  21.  }  
  22. // Create a new object and passes three parameters   
  23.  $f = new MyClass('20px','red','Object Oriented Programming');  
  24.  ?>  

Output :
method red string

PHP Destructors methods

  • Destructor is the counterpart of constructor.
  • A destructor function is called when the object is destroyed
  • A destructor function cleans up any resources allocated to an object after the object is destroyed.
  • A destructor function is commonly called in two ways: When a script ends or manually delete an object with the unset() function
  • The 'destructor' method starts with two underscores (__).

The general syntax for destructor declaration follows :

function __destruct
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.

Example :

<?php  
  1. // Define a class  
  2. class MyClass  
  3. {  
  4.  function __construct()   
  5.   {  
  6.     echo 'w3resource'.'<br>';  
  7.     $this->name = "MyClass";  
  8.   }  
  9.  function __destruct()   
  10.   {  
  11.     echo "Destroying " . $this->name . "<br>";  
  12.   }  
  13. }  
  14. $obj = new MyClass();  
  15. ?>  

Output :
w3resource
Destroying MyClass

PHP : Using multiple instances of the same class

In the following example we have created multiple objects (instances) of the same class and passes different values.

<?php  
  1. // Define a class  
  2. class Myclass  
  3.  {  
  4. // Declaring three private varaibles  
  5.  private $font_size;  
  6.  private $font_color;  
  7.  private $string_value;  
  8. // Declarte construct method which accepts three parameters and the method customize_print()  
  9.  function __construct($font_size,$font_color,$string_value)  
  10.  {  
  11.  $this->font_size = $font_size;  
  12.  $this->font_color = $font_color;  
  13.  $this->string_value = $string_value;  
  14.  $this->customize_print();  
  15.  }  
  16. // Declare a method for customize print   
  17.  function customize_print()  
  18.  {  
  19.  echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";  
  20.  }  
  21.  }  
  22. // Create first object and passes three parameters   
  23.  $a = new MyClass('30px','red','Object Oriented Programming');  
  24. // Create second object and passes three parameters   
  25.  $b = new MyClass('25px','blue','Object Oriented Programming');  
  26. // Create third object and passes three parameters   
  27.  $c = new MyClass('20px','green','Object Oriented Programming');  
  28. // Create fourth object and passes three parameters   
  29.  $d = new MyClass('15px','black','Object Oriented Programming');  
  30.  ?>  

Output :

multiple objects

 

PHP : spl_autoload_register()

Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class). Traditionally __autoload() function was used to automatically load classes. As of PHP 5.1.2 a new function spl_autoload_register() is introduced which provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

Syntax

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Parameter

Name Description
autoload_function The autoload function being registered. If no parameter is provided, then the default implementation of spl_autoload() will be registered.
throw This parameter specifies whether spl_autoload_register() should throw exceptions when the autoload_function cannot be registered.
prepend If true, spl_autoload_register() will prepend the autoloader on the autoload stack instead of appending it.

Return values

Returns TRUE on success or FALSE on failure.

You can use spl_autoload_register() function in following way :

<?php  
  1.  spl_autoload_register(function ($class)   
  2.  {  
  3.  include 'classes/' . $class . '.class.php';  
  4.  });  
  5. ?>  

Example :

At first  we will create two classes and store them in /php/classes-objects/resource path :

class1.php

<?php  
  1. // Define a class  
  2. class class1  
  3.  {  
  4. // Declaring two private varaibles  
  5.  private $font_color;  
  6.  private $string_value;  
  7. // Declarte construct method which accepts two parameters and the method customize_print1()  
  8.  function __construct($font_color,$string_value)  
  9.  {  
  10.  $this->font_color = $font_color;  
  11.  $this->string_value = $string_value;  
  12.  $this->customize_print1();  
  13.  }  
  14. // Declare a method for customize print   
  15.  function customize_print1()  
  16.  {  
  17.  echo "<p style=color:".$this->font_color.";>".$this->string_value."</p>";  
  18.  }   
  19.  }  
  20. ?>  

class2.php