CommonLounge Archive

PHP: Object Oriented Programming

September 19, 2018

In this tutorial, you’ll learn about Object Oriented Programming, or OOP for short. OOP allows you to create large projects while still keeping things easy to understand.

Class and Object

The world around is made of up different types of objects - planets, cars, computers, animals, and so on. In OOP, a type of object is represented by a class. Specific planets - such as Earth, Mars, Jupiter, etc and specific cars such as your car, my car, and the taxi driving by outside your house are each represented by an object.


In programming, a class is a programmer-defined data-type. A class contains some data, and methods / functions to use that data.

Let’s look at how to define a class. First we have to define a PHP class, where the name of the class should be (preferably) same as the filename:

<!-- vehicle.php -->
<?php
  class Vehicle {
      public function getName() {
          echo 'Car' . '<br>';
      }
      public function getCapacity() {
          echo 4 . '<br>';
      }
  }
  $obj = new Vehicle();
  $obj->getName();
  $obj->getCapacity();
?>

Output:

Car
4

Let’s break this down and understand how this works.

Creating a Class in PHP

class Vehicle {
    public function getName() {
        echo 'Car';
    }
    public function getCapacity() {
        echo 4;
    }
}

First, we create a class and call it Vehicle. Inside the class, we have two public functions, each of which just has an echo statement. Functions such as these, which are defined inside a class, are called methods. A public function means that these functions can be accessed from anywhere - we will explain this in more detail later in the tutorial.

Creating an Object in PHP

$obj = new Vehicle();

Next, we create an object and assign it to variable $obj. The object is created with the help of new keyword. Although we only create one object here, we can create any number of objects of the same class.

Calling Member Functions

$obj->getName();
$obj->getCapacity();

Once the object is created, we can access the variables and methods of the class with the -> operator. Here, we call the getName() and the getCapacity() functions.


Multiple Objects and Class Variables

Now, let’s say we want different objects of the class Vehicle. Each object has properties (like name and capacity).

If we want to create different objects of a class with different properties, this is how we would do it:

<!-- vehicle.php -->
<?php
   class Vehicle {
      public $name;
      public $capacity;
      public function getName() {
          echo $this->name . '<br>';
      }
      public function getCapacity() {
          echo $this->capacity . '<br>';
      }
      public function setName($name) {
        $this->name = $name;
      }
      public function setCapacity($capacity) {
        $this->capacity = $capacity;
      }
   }
   $obj1 = new Vehicle();
   $obj1->setName("Bike");
   $obj1->setCapacity(2);
   $obj1->getName();
   $obj1->getCapacity();
   $obj2 = new Vehicle();
   $obj2->setName("Car");
   $obj2->setCapacity(4);
   $obj2->getName();
   $obj2->getCapacity();
?>

This will display:

Bike
2
Car
4

We created two public variables inside the class. Variables such as these, which are defined inside a class, are called properties. We also added two more methods setName() and setCapacity().

You might be wondering what does $this mean? The variable $this is a special variable and it is used to refer to the “current” object from inside the member functions. For example, when we call $obj1->setName("Bike"), the setName method can access $obj1 as $this. Hence, in this case, $this->name refers to the variable $name belonging to $obj1.

In the above example, we then create two objects with different properties (name and capacity) and display them.

Constructor

In the above example, we created two objects and then assigned specific values to the properties of those objects. There’s a better way to initialize different objects of a class using a Constructor.

A constructor is a special function which is called automatically whenever an object is created. In PHP, the constructor function is called __construct(). You can define the function to accept as many arguments as you would like to.

Here’s a sample constructor for the Vehicle class and which will initialize $name and $capacity of the vehicle at the time of object creation:

function __construct($name, $capacity) {
   $this->name = $name;
   $this->capacity = $capacity;
}

Now we don’t need setName() or setCapacity() functions to set name and capacity. We can initialize these two member variables at the time of object creation itself! Check the following example:

<!-- vehicle.php -->
<?php
  class Vehicle{
    public $name;
    public $capacity;
    function __construct($name, $capacity) {
       $this->name = $name;
       $this->capacity = $capacity;
    }
    public function getName() {
        echo $this->name . '<br>';
    }
    public function getCapacity() {
        echo $this->capacity . '<br>';
    }
  }
  $obj1 = new Vehicle("Bike", 2);
  $obj2 = new Vehicle("Car", 4);
  $obj1->getName();
  $obj1->getCapacity();
  $obj2->getName();
  $obj2->getCapacity();
?>

This will produce the following result:

Bike
2
Car
4

We just implemented the same thing as the previous example, but with fewer lines of code using a constructor!

Inheritance

So far, we looked at classes and objects. You saw how to define a class, and how to create objects of that class. Each of these objects has properties and methods which are defined in the class.

Often, there are situations where we want to define subtypes of a particular type. For example, stars and planets and subtypes of celestial bodies. Horses and lions are subtypes of animals. Circles and squares are subtypes of shapes. In OOP, we model subtypes using inheritance.

To define a PHP class which inherits from a parent class, we use the extends keyword, like so:

class Child extends Parent {
   // definition body
}

Since the Child class extends the Parent class:

  • It has all the member variables (properties) of the parent class.
  • It has all the member functions (methods) as the parent class. By default, these methods will work the same way as they do in the parent class, but the child class can overwrite it if required (you’ll see an example of this in a few minutes).

Inheritance example

Let’s create a class B which inherits from class A and adds more functionality:

<?php 
  class A {
    public function showA() {
      echo 'I am from A! <br>';
    }
  }
  class B extends A {
    public function showB() {
      echo 'I am from B! <br>';
    }
  }
  $a = new A();
  $b = new B();
  $a->showA(); // I am from A! 
  $b->showA(); // I am from A! 
  $b->showB(); // I am from B! 
?>

As you can see, now apart from the inherited method showA(), objects of class B have an additional method showB().

Keep in mind that the reverse is not true! Only the child class inherits methods from the parent class. Objects of the parent class do not inherit methods from the child class. In the example above, $a->showB(); will throw an error.

Single Level Inheritance

The above code is an example of single level inheritance. Single level inheritance is the simplest type of inheritance. There are two classes, one parent class and one child class.

Diagram: Single level inheritance

Here, Class A is the parent while Class B is the child class.

Hierarchical Inheritance

Another widely used inheritance type is hierarchical inheritance. Here, we have multiple children who inherit from a single parent.

<?php 
  class A {
    public function showA() {
      echo 'I am from A! <br>';
    }
  }
  class B extends A {
    public function showB() {
      echo 'I am from B! <br>';
    }
  }
  class C extends A {
    public function showC() {
      echo 'I am from C! <br>';
    }
  }
  class D extends A {
    public function showD() {
      echo 'I am from D! <br>';
    }
  }
  $a = new A();
  $b = new B();
  $c = new C();
  $d = new D(); 
  $a->showA(); // I am from A! 
  $b->showA(); // I am from A! 
  $b->showB(); // I am from B! 
  $c->showA(); // I am from A! 
  $c->showC(); // I am from C! 
  $d->showA(); // I am from A! 
  $d->showD(); // I am from D! 
?>

Let’s try to visualize this code:

Diagram: Hierarchical inheritance

In this example, three child classes inherit from one parent class. Class A is the parent class (also known as the base class). Objects of class B, C or D can access the methods defined in class A.

Note: Children classes are independent of each other. That is, an object of class B cannot access methods defined in class C or class D (which are siblings of class B).

This is just a simple example of hierarchical inheritance. We can extend the logic further by creating more child classes which inherit from class B, C and D and so on.

A realistic illustration

Let’s see another example of hierarchical inheritance. We want to create three classes, Rectangle, Circle and Triangle which inherit from class Shape. Each of these classes defines a constructor, and also how to calculate the perimeter and area. The base Shape class has the display method to display the calculated values.

<?php
  class Shape {
      public $name; 
      public function display() {
          echo "I am a " . $this->name . " with ";
          echo "perimeter " . $this->perimeter() . " and ";
          echo "area " . $this->area() . "<br>";
      }
  }
  class Rectangle extends Shape {
      public $length;
      public $breadth;
      function __construct($length, $breadth) {
          $this->name = "Rectangle";
          $this->length = $length;
          $this->breadth = $breadth;
      }
      public function perimeter() {
          return 2 * ($this->length + $this->breadth);
      }
      public function area() {
          return $this->length * $this->breadth; 
      }
  }
  class Circle extends Shape {
      public $radius;
      function __construct($radius) {
          $this->name = "Circle";
          $this->radius = $radius;
      }
      public function perimeter() {
          return 2 * 3.14 * $this->radius;
      }
      public function area() {
          return 3.14 * $this->radius * $this->radius; 
      }
  }
  class Triangle extends Shape {
      public $side1;
      public $side2;
      public $side3;
      function __construct($side1, $side2, $side3) {
          $this->name = "Triangle";
          $this->side1 = $side1;
          $this->side2 = $side2;
          $this->side3 = $side3;
      }
      public function perimeter() {
          return $this->side1 + $this->side2 + $this->side3;
      }
      public function area() {
          $p = $this->perimeter() / 2.0;
          return sqrt($p * ($p - $this->side1) * ($p - $this->side2) * ($p - $this->side3)); 
      }
  }
  $rect = new Rectangle(5, 4);
  $rect->display();
  $circ = new Circle(5);
  $circ->display();
  $tri = new Triangle(3, 4, 5);
  $tri->display();
?>

Output:

I am a Rectangle with perimeter 18 and area 20
I am a Circle with perimeter 31.4 and area 78.5
I am a Triangle with perimeter 12 and area 6

A few interesting things to notice in the above example

  • The Rectangle, Circle and Triangle classes don’t have to individually define the display() method. They inherit the method from the base class Shape.
  • Each of the three classes implements a perimeter() and an area() method, within which they do different types of calculations. However, from the outside, these functions all look the same. That is, you can do echo $rect->area(), echo $tri->area() and echo $circ->area().

Public, Private and Protected Members

All our previous examples used public variables and functions. In general, each method and property in a class can have different visibility. In PHP, there are three types of visibility - public, protected and private. Here’s what they do:

  • public - allows everyone to access the method/property. This is the default visibility in PHP class when no keywords are prefixed to a method/property.
  • private - does not allow anyone except the class itself to access the method/property.
  • protected- allows the class itself, as well as any parent / children classes to class the method/property.

The public visibility is the only way to access methods or functions from outside the class. If you wish to limit the visibility of the members of a class then you define class members as private or protected.

Illustration of Public and Private Members

By designating a member private, you limit its visibility to the class in which it is declared.

class MyClass {
   private $id;
   public $name;
   function __construct() {
       $this->id = 1;
       $this->name = "Commonlounge";
   }
   public function myPublicFunction() {
      return "I'm visible everywhere!";
   }
   private function myPrivateFunction() {
      return "I'm not visible outside!";
   }
}
$obj = new MyClass();
echo $obj->name . "<br>"; 
// echo $obj->id . "<br>";      // Not allowed. Will give error! 
echo $obj->myPublicFunction(); 
// $obj->myPrivateFunction();   // Not allowed. Will give error!  

As you can see, the private properties and methods are not visible from outside, whereas the public properties and methods are.

Illustration of Public, Protected and Private Members

By designating a member protected, you limit its visibility to the class in which it is declared, or to the parent / child classes.

class ParentClass {
   private $id;
   protected $age;
   public $name;
   function __construct() {
       $this->id = 1;
       $this->name = "Commonlounge";
       $this->age = 25;
   }
}
class ChildClass extends ParentClass { 
   public function displayId() {
      echo $this->id;   // Not allowed. Will give error! 
   }
   public function displayAge() {
      echo $this->age; // Allowed. Protected variables can be accessed
   }
   public function displayName() {
      echo $this->name; // Allowed. Public variables can be accessed
   }
} 
$obj = new ChildClass();
// echo $obj->id;    // Not allowed. Private. Will give error! 
// echo $obj->age;   // Not allowed. Protected. Will give error! 
echo $obj->name;     // Allowed. Public. 
$obj->displayId();   // Not allowed. $this->id; id is private. Will give notice!
$obj->displayAge();  // Allowed. $this->age; age is protected. 
$obj->displayName(); // Allowed. $this->name; name is public. 

Summary

In this tutorial, you learned about:

  1. Class and object: how to write a class with methods and properties, and how to create an instance / object of that class.
  2. Constructor: a special function which is called automatically when an object of the class is created. You can use the constructor to initialize an object’s properties.
  3. Inheritance: you can use inheritance to implement sub-types. The base class implements all the logic common to all the types, and the individual classes which inherit from the base class implement the logic that is specific to each sub-type.
  4. Visibility: private, public and protected keywords are used to limit the visibility of a property or method in a class.

OOP concept is used in practically all real-world PHP applications. You just completed one of the most important tutorials in this course. Congratulations!


© 2016-2022. All rights reserved.