JavaScript Tutorial

Object Oriented Programming with PHP

Object Oriented Programming (OOPs) is based on the concept of Objects and
Classes. Features of OOPs are :

  • Classes & Objects: A class is a programming block composed of its own properties and methods. An object is an instance of the class to access the class components.
  • Encapsulation: It binds the data and methods into a single entity.
  • Abstraction: It means to hide the implementation details from the user and display only essential information.
  • Inheritance: It involves deriving a new class from an existing class while inheriting the required information from the base class.
  • Polymorphism: It involves the concept of using different classes with the same interface.

Classes & Objects

Class is a template posing some properties and behaviour. Real world entities are considered as objects and are binded in a class. For example: Suppose we have a
class named as Person. A person can have properties like name, age, height and weight etc.. Also behaviour may include walking, sleeping etc. which commonly belongs to all the objects of this class.

Defining a class:
<?php
   class Person{
      public $name;
      public $age;
      function set($name, $age){
         $this->name = $name;
         $this->age = $age;
      }
      function get(){
         echo "Name -> ".$this->name;
         echo "<br>";
         echo "Age ->".$this->age;
      }
   }
?>

A Class is just a template and functions with the help of objects only.

Objects

Each object carries all the properties and methods of the related class. Objects are created as:

<?php
   class Person{
      public $name;
      public $age;
      function set($name, $age){
         $this->name = $name;
         $this->age = $age;
      }
      function get(){
         echo "\nName -> ".$this->name;
         echo "\nAge ->".$this->age;
      }
   }
   $obj1 = new Person();
   $obj2 = new Person();
   $obj1->set("John", 25);
   $obj2->set("Chris", 30);
   $obj1->get();
   $obj2->get();

/*	
------OUTPUT-----
Name -> John
Age ->25
Name -> Chris
Age ->30

*/
?>

Constructors & Destructors

1. Constructors are used to initialize objects upon the creation of an object. In PHP, __construct() method is used to declare a constructor and will be automatically called when an object is created. For Example:

<?php
   class Person{
      public $name;
      public $age;
      function __construct($name, $age){
         $this->name = $name;
         $this->age = $age;
      }
      function get(){
         echo "\nName -> ".$this->name;
         echo "\nAge ->".$this->age;
      }
   }
   $obj1 = new Person("John", 25);
   $obj2 = new Person("Chris", 30);
   $obj1->get();
   $obj2->get();
?>

As we can see, lines of code got reduced with the help of constructors.

Without using constructors With the use of constructors
$obj1 = new Person();
$obj2 = new Person();
$obj1->set("John", 25);
$obj2->set("Chris", 30);
$obj1->get();
$obj2->get()
$obj1 = new Person("John", 25);
$obj2 = new Person("Chris", 30);
$obj1->get();
$obj2->get();

2. Destructors are used to destroy the object when they are out of scope and no longer in use. __destruct() function is used to serve the purpose of a destructor and is automatically called at the end of the script.

<?php
   class Person{
      public $name;
      public $age;
      function __construct($name, $age){
         $this->name = $name;
         $this->age = $age;
      }
      function __destruct(){
         echo "\nName -> ".$this->name;
         echo "\nAge ->".$this->age;
      }
   }
   $obj1 = new Person("John", 25);
   $obj2 = new Person("Chris", 30);

/*
---OUTPUT---
Name -> Chris
Age ->30
Name -> John
Age ->25
*/
?>

CONSTANTS

Unlike variables, constants cannot be changed once they are declared. ‘const’ keyword is used to declare constants in PHP. Class constants are case-sensitive.

/* Syntax */
const PIE = 3.14;

Accessing Constants:

To access constants, you can use the following syntax:

Outside the class: 
ClassName::CONSTANT_NAME
Inside the class:
self::CONSTANT_NAME
<?php
   class ABC{
      const PIE = 3.14;
      public function display(){
         echo self :: PIE;      // Inside the class
      }
   }
   echo ABC :: PIE;      // Outside the class
   echo "<br>";
   $obj = new ABC();
   $obj->display();
?>

Inheritance

Inheritance is the concept of deriving a new class from an existing class. The new class will automatically inherit all the public and protected properties of the existing class. The class which is inherited is called as Child Class and the class from whom the properties are inherited is called as Parent Class or Base Class.

Inheritance uses the 'extends' keyword for its implementation.

Inheritance is implemented using three access modifiers :

  • Public
  • Protected
  • Private

1. Public: Members declared public are accessible by the class in which they are declared and also in all the classes inherited. Let's code something using inheritance.

<?php
   class parentClass{
      public $a;
      public $b;
      public function __construct($a, $b){
         $this->a = $a;
         $this->b = $b;    
      }   	 
      public function display(){
         echo "A = ".$this->a."\nB = ".$this->b."\n";
      }
   }
   class child extends parentClass{
      public function sum(){
         echo "Sum is -> ".($this->a+$this->b);
      }
   }
   $obj = new child(10, 20);
   $obj->display();
   $obj->sum();

/*
--- OUTPUT ---
A = 10
B = 20
Sum is -> 30
*/
?>

2. Protected: Members declared protected are accessible by the class in which they are declared and also in the subclasses.

<?php
   class parentClass{
      public $a;
      public $b;
      public function __construct($a, $b){
         $this->a = $a;
         $this->b = $b;    
      }
      protected function display(){
         echo "A = ".$this->a."\nB = ".$this->b."\n";
      }
   }
   class child extends parentClass{
      public function sum(){
         $this->display();      // Calling protected method 
         echo "Sum is -> ".($this->a+$this->b);
      }
   }
   $obj = new child(10, 20);
   $obj->sum();

/*
---OUTPUT---
A = 10
B = 20
Sum is -> 30
*/
?>

Calling protected methods outside the class will generate an error. Hence, we have called it inside the child class.

3. Private: Members declared private are accessible by the class in which they are declared only.

<?php
   class parentClass{
      private $a;
      public $b;
      public function __construct($a, $b){
         $this->a = $a;
         $this->b = $b;    
      }
      public function display(){
         echo "A = ".$this->a."\n";
      }
   }
   class child extends parentClass{
      public function display2(){
         echo "B = ".($this->b);
      }
   }
   $obj = new child(10,20);
   $obj->display();
   $obj->display2();

/*
---OUTPUT---
A = 10
B = 20
*/
?>

$a is the private member of class ParentClass and is not accessible in Child Class. Although, $b is easily accessible in both Parent and Child Class for being a public member.


Final Keyword

In PHP, the final keyword is used to indicate that a class, method or property cannot be extended or overridden by any child classes.

When used with a class, the final keyword prevents other classes from extending the final class. For example:

final class parentClass {
    // class definition
}

In the above code, the parentClass is marked as final, so it cannot be extended by any other class.

When used with a method, the final keyword prevents the method from being overridden in child classes. For example:

class parentClass {
    final public function display() {
        // method definition
    }
}

class childClass extends parentClass {
    // This will produce a Fatal error: Cannot override final method parentClass::display()
    public function display() {
        // overridden method definition
    }
}

In the above code, the display() is marked as final in the parentClass, so it cannot be overridden in childClass.

When used with a property, the final keyword prevents the property from being re-declared in child classes. For example:

class parentClass {
    final protected $age = 32;
}

class childClass extends parentClass {
    // This will produce a Fatal error: Cannot redeclare protected property parentClass::$age
    protected $age = 33;
}

In the above code, the $age is marked as final in the parentClass, so it cannot be re-declared in childClass.


Abstract Methods

Abstract methods are methods declared in a parent class but do not have a definition in the parent class. Instead, they are defined in the child class. For instance:

+-----------------------------------+
|       Abstract Parent Class       |
+-----------------------------------+
| + method1()                      |
| + abstract method2()             |
| + method3()                      |
+-----------------------------------+
        |                       |
   +-------------+        +-------------+
   |   Child 1   |        |   Child 2   |
   +-------------+        +-------------+
   | + method2() |        | + method2() |
   +-------------+        +-------------+

In this diagram, we have an abstract parent class with three methods: method1(), abstract method2(), and method3(). The abstract method method2() has no implementation in the parent class and is declared using the abstract keyword.

Two child classes Child 1 and Child 2 inherit from the parent class. Child 1 implements the abstract method method2() with its own implementation, while Child 2 also implements method2() with a different implementation.

Abstract methods allow us to define method signatures in an abstract class without providing an implementation. This enforces child classes to implement these methods with their own implementation, ensuring that these methods are implemented consistently across all child classes.

When using abstract methods in PHP, there are some important points to keep in mind:

  • The child class method must have the same name as the abstract method declared in the parent class.
  • The abstract method in the parent class must be declared either as public or protected.
  • The number of required arguments in the child class method must be the same as in the abstract method declared in the parent class.
Let's code an example
<?php
   abstract class Shape{
      abstract public function perimeter();
   }
   class Rectangle extends Shape{
      public $l;
      public $b;
      public function __construct($l, $b) {
         $this->l = $l;
         $this->b = $b;
      }
      public function perimeter(){
         $res = 2 * ($this->l + $this->b);
         return $res;
      }
   }
   class Square extends Shape{
      public $s;
      public function __construct($s) {
         $this->s = $s;
      }
      public function perimeter(){
         $res = 4 * $this->s;
         return $res;
      }
   }
   $obj1 = new Rectangle(10,20);
   echo "Perimeter of Rectangle -> ".$obj1->perimeter();
   $obj2 = new Square(10);
   echo "\n Perimeter of Square -> ".$obj2->perimeter();

/*
---OUTPUT---
Perimeter of Rectangle -> 60
Perimeter of Square -> 40
*/
?>

Interfaces

Interfaces help us to define which methods a class can implement. They are declared using interface keyword. An interface is similar to abstract classes with the following differences :

  • Interfaces do not pose any properties like abstract classes.
  • All the methods in an interface are abstract. 
  • Classes can use interfaces meanwhile implementing the concept of inheritance as well.
  • Interface methods are supposed to be public only while abstract classes can use protected and private as well.

To implement an Interface implements keyword is specified.

<?php
   interface Shape{
      public function sides();
   }
   class Square implements Shape {
      public function sides() {
         echo "It has 4 sides";
      }
   }
   $obj = new Square();
   $obj->sides();

/*
---OUTPUT---
It has 4 sides
*/
?>

Static Methods

The methods who can be called directly without creating any instance of that class, are known as static methods.

They are declared using a static keyword and are accessed as follows:

ClassName::staticMethod();

Code example:

<?php
   class hello {
      public static function display() {
         echo "Hello";
      }
   }
   hello::display();
?>

In order to use static methods in the same particular class, ‘self’ keyword is used. 

For example: 

self::display();

In order to use static methods in some other class, methods must be declared public.

Code example:

<?php
   class hello {
      public static function display() {
         echo "Hello";
      }
   }
   class hello2 {
      public function display2() {
         hello::display();
      }
   }
?>

A class can also have static properties, they are accessed the same way the static methods are accessed.

Here is a code example:

<?php
   class stat_prop{
      public static $val = 10;
      public function staticValueFn() {
         return self::$val;
      }
   }
   $obj = new stat_prop();
   echo $obj->staticValueFn();
?>
Go back to Previous Course