OOPs Concepts in PHP

According to Indeed.com, the demand for PHP developers has massively increased to 834% since January 2020, and, it is today the fastest-growing tech job across the industry, today. 

Let's get started with the first concept.

What is PHP? 

/OOPsInPHP_1

PHP (or Hypertext Preprocessor) is an open-source language that is used for scripting and general-purpose programming, developed by Rasmus Lerdorf, a Danish-Canadian developer in 1994. Millions of programmers and developers for web and application development use this scripting language. PHP allows you to write code that can efficiently produce dynamic content and scripts that execute on the server.  PHP is quite flexible with usage, as it can be installed and used on almost all popular operating systems such as Windows, macOS, Linux, RISC OS, and many variants of UNIX as well. 

PHP is a versatile language and can serve the achievement of  various tasks, but it is mainly used for the following purposes:

  • Scripting for server-side development: Server-side development is the field in which PHP has been widely used since it has arrived. To use it for developing applications that run on the server, you need to have the PHP module, a web server, and a browser.  
  • Scripting for command-line usage: The PHP language like many other programming languages can also run without having to execute it on a server. You can easily execute PHP scripts on a command-line using the parser for PHP. This can be useful when you want to develop applications such as shell applications.
  • Development of Applications: PHP can also be used to develop applications such as desktop applications and cross-platform applications. To write a desktop application, since there is a requirement of the graphical interface, you need to install additional tools like PHP-GTK.

PHP follows the organizing principles of functional, procedural, imperative, and object-oriented programming. You can use any of them or even a mixture of these programming paradigms. In this article, you will look into the OOPs methodology introduced in PHP. OOPs concepts in PHP can help the developers develop real-world applications that support reusability and are dynamic and complex in nature. 

What is OOPS?

Object-Oriented Programming or simply OOPs is a programming approach or paradigm that gives its prime consideration to the data and its associated functions. It uses the concept of wrapping up the data as an object-entity having its associated properties, to provide higher security and less exposure to the data. As nothing is more important than the data itself, this approach is highly in use and widely accepted by programmers worldwide. The programming languages that do not support OOPs methodologies and their concepts are slowly getting deprecated, and the languages that are now being developed, support OOPs and are the extended version of object-oriented programming. 

To relate programming with the real world, this methodology considers everything in the world as an entity or an object, and every object has some of its attributes or properties. So, the concept of the classes and objects can be applied to model an entire application. The overall development of an application in an object-oriented perspective can be summarized as:

  • The object-oriented analysis describes the application’s functionality.
  • The application’s architecture is described by designing it using an object-oriented approach.
  • The application’s implementation is described by programming it using the object-oriented method.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Object-Oriented Concepts and Principles in PHP

The PHP programming language is based on the paradigm of Object-Oriented Programming (OOPs). Object-Oriented Programming is an umbrella under which the features of Object-Based programming resides. Meaning, it consists of all the characteristics of object-based programming and gets the better of its limitations by executing inheritance so that through programming, you can solve the problems based on real-life situations. Object-oriented programming was created to get better at the drawbacks of usual programming techniques. The OOPs concepts in PHP have been developed on some concepts that make it achieve its aim of getting the better of the drawbacks or deficiency of usual programming techniques. 

Before diving deep into PHP, you have to learn about the basic OOPs concepts in PHP that are the pillars of OOPS:

  • Class: The class is the blueprint that is used to hold the objects along with their behavior and properties. In PHP, the class name should be the same as that of the file name with which it has saved the program. A class is a user-defined data type that consists of two entities: Data Members and Member Functions.
  • Data Members: Data Members are the variables that can be of the data type var in PHP. Data Members act as the data for the source code with which you can meddle around. Data members can have three types of visibility modes that decide the access permission of these members. These modes are private, protected, and public.
  • Member Functions: Those data members that have visibility mode as private, and cannot be accessed directly by the class objects. In such cases, member functions come into play. Those functions that are specifically created to access private data members are known as member functions. 
  • Objects: An object in a class is an instance that has its own behavior and property. Objects can be related to the entities in real life. It considers everything around you as an object with some of its attributes. For eg: a spaceship is an object. It has properties like fuel, color, speed, material, etc. and it can have functions like launching_in_space, landing_on_a_planet, etc. 

When you define a class, with all its data members and member functions, then every instance or object of that class will occupy the memory equal to the memory allocated to the data members of that class. For eg: if a class has been allocated 10 bytes of memory for its data members, and if there are three objects of this class, namely obj1, obj2, and obj3, 10 bytes of memory will be allocated to each of the objects.

  • Data Abstraction: Abstraction is referred to the concept of giving access to only those details that are required to perform a specific task, giving no access to the internal details of that task.

You can understand it better with an example. 

For eg,. If you are driving a car, you have the knowledge of critical aspects like how to move the handle, how the clutch, accelerator, brakes work, and so on. To drive well, you needn’t necessarily have to be an expert on the more mechanical aspects of how a car functions - like how the engine works, how the clutch is wired, etc. You just changed the gears or applied the brakes. The inside mechanism is not visible to the driver. This whole thing is known as Abstraction, where you know only the basic knowledge to drive the car without including the inside mechanism of the vehicle.

  • Data Encapsulation: Data Encapsulation is one of the most important notions of OOPS. It is the way of binding both the data and the functions that get executed on the given data under a single roof. These functions are member functions in PHP. You do not have permission to access the data directly. Create a member function, in order to manipulate or use that given data. This data is not visible to you, so it is safe from any kind of manipulation by an outsider. Data and its member functions are said to be encapsulated in a single cell.
  • Modularity: Modularity is the technique of dividing the program into subprograms or functions. The advantages that modularity can attain are:
    • It decreases the complex nature of the article
    • It generates various well-structured documentation increasing the quality of the program

A module is a separate unit in itself. Hence you can execute a separate module as it is connected to other modules in some manner. All the modules act together as a single unit to achieve the aim of the program. In OOPs, classes and objects form the basic foundation of a system. 

  • Inheritance: Inheritance is one of the most vital concepts of OOPs which is essential to know, to get a deep insight into the whole concept of Object-Oriented Programming. Inheritance in PHP has made it possible to use reusability as a tool to write clean and efficient programs. Inheritance in PHP is of 3 types, which you will see in detail in this article later on. These three types are as follows:
  • Single Inheritance
  • Hierarchical Inheritance
  • Multilevel Inheritance

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Defining PHP classes

You can define your own classes in PHP and declare required data members and the member functions in it using the following syntax:

Syntax to Define a Class:

// Boilerplate for a class in PHP<?php     class Class_Name {     }?>

As you can see above, class_name is the name of the class and it should be the same as that of the file with which you have saved your code.

Syntax for Declaring Data Members and Member Functions:

// Syntax to define PHP class<?php   class Class_Name {      // Syntax for declaring data members      var $data_member_name;      // Syntax for member function     function member_function_name ($argument_name_1, $argument_name_2) {         [..]      }      [..]   }?>

Description of the Parameters:

  • class: The keyword class that needs to be given at the start while defining a class. Just like some other programming languages such as C++, Java, and JavaScript. 
    • Class_Name: This is the name of the class that is provided after the keyword class and should be the name of the file. For eg: for a file saved as myClass.php, the class name should also be myClass.
  • data_member_name: This is the name of the data member of your class. You can declare any number of data members in your class, using the keyword var.
  • member_function_name: This is the name of the member function of your class, you can define a function in your class by using the keyword function before the name of the function.
  • argument_name: This is the argument of the function that is given while declaring it.

Note: The syntax for defining member functions in a class in PHP is similar to the usual functions that you define in PHP.

The following example will illustrate classes in PHP. 

Consider there is a subject, which can have a specialized field as its property. The following program defines a class named subject which has a constructor and a member function that prints the name of the specialized field of that subject.

<?php// define a class named subjectclass subject{    // defining the constructor of the class    public function __construct() {        echo 'I am the constructor' .PHP_EOL;    }    // defining a member function named     // field_subject    // with one argument named field    public function subject_field($field) {        echo 'This subject is specialised in ' . $field .PHP_EOL;    }   }// declare an object of the class // named obj1 using the "new" keyword.// as soon as an object is created,// the default constructor is automatically called.$obj1 = new subject;        // here the default constructor of                            // the class subject is called                             // automatically.// calling the function subject_field// by passing it "Mathematics" as an argument$obj1->subject_field("Mathematics");?>

OOPs_In_PHP_1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Creating Objects in PHP

Class is one of the most critical OOPs Concepts in PHP. A class can have any number of instances or objects. All the objects of a class will have access to all the data members and member functions of that class. To create an object of a class in PHP, the new keyword is used.

The Syntax for Creating an Object in PHP:

// define a classclass class_name {   // declare data members   // and define member functions...}// creating objects of the class// named class_name using the// "new" keyword.$object_name_1 = new class_name;$object_name_1 = new class_name;

After creating an object, you can use it to call the member functions, or even assign some value to the data members of that class.

The following example will illustrate how to call member functions in PHP. 

Consider the same example discussed earlier. There is a subject, which can have a specialized field as its property. The following program defines a class named subject which has a constructor and a member function that prints the name of the specialized field of that subject. You can create different objects for the class subject.

<?php// define a class named subjectclass subject{    // defining the constructor of the class    public function __construct() {        echo 'I am the constructor' .PHP_EOL;    }    // defining a member function named     // field_subject    // with one argument named field    public function subject_field($field) {        echo 'This subject is specialised in ' . $field .PHP_EOL;    }   }// declare an objects of the class // using the "new" keyword.$obj1 = new subject;      /** here the default constructor **/$obj2 = new subject;      /** will be called for **/       $obj3 = new subject;      /** every object created. **/   // calling the function subject_field// by passing it "Mathematics", "English", // and "Computer Science" as the arguments. $obj1->subject_field("Mathematics");$obj2->subject_field("English");$obj3->subject_field("Computer Science");?>

OOPs_In_PHP_2

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Calling Member Functions in PHP

The objects of a class can be used to access the member function of that class. You have to use the “arrow” (i.e. “->”) operator to achieve this. 

Syntax to Access Member Functions and Data Members of a Class:

// define a classclass class_name {   // declare data members   var $data_member;       // a member function of the class   public function function_name() {       // define the function here   }} // creating objects of the class// named class_name using the// "new" keyword.$object_name_1 = new class_name;$object_name_2 = new class_name; // access member function using// "arrow" operator.$object_name_1->function_name();$object_name_2->function_name();The following example will illustrate how to call member functions in PHP. <?php   class Furniture {      // declare member variables       var $name;      var $cost;      // define the member functions      function Name($name){         $this->name = $name;      }      function printName(){         echo $this->name .PHP_EOL;      }      function Cost($cost){         $this->cost = $cost;      }      function printCost(){         echo $this->cost .PHP_EOL;      }        }// create objects for class "Furniture"$Table = new Furniture();$Sofa = new Furniture();$Cupboard = new Furniture();// call member functions // by passing string arguments to them.$Table->Name( "Table" );$Sofa->Name( "Sofa" );$Cupboard->Name( "Cupboard" );// call functions by passing // integer costs as arguments to them.$Table->Cost( 7000 );$Sofa->Cost( 55000 );$Cupboard->Cost( 25000 );// call functions to // print the name of the furniture.$Table->printName();$Sofa->printName();$Cupboard->printName();// call functions to // print the cost of the furniture.$Table->printCost();$Sofa->printCost();$Cupboard->printCost();?>

OOPs_In_PHP_3.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Constructor 

Constructor is a type of a member function of the class in PHP. Constructors are a critical part of classes as they act as a blueprint to create objects of the class. Unlike other member functions, a constructor does not need to be called. It gets automatically called once you create the object.

PHP offers three types of constructors:

  • Default Constructor: Default constructors do not accept an argument. You can pass the values to default constructors dynamically.
  • Parameterised Constructor: These constructors accept arguments and can also pass values to the data members.
  • Copy Constructor: Copy constructors take addresses of the other objects as arguments.

Destructor

Destructor is also a special member function of a class in PHP. The purpose of the destructor is exactly the opposite of the purpose of the constructor. The destructor gets called when you delete an object of the class from the memory. The destructor does not accept any kind of argument and does not return anything.

The following example will illustrate destructors in PHP. 

<?php// define a class named Furnitureclass Furniture {  public $price;  public $type;  // constructor of the class  function __construct($price, $type) {    $this->price = $price;    $this->type = $type;  }  // destructor of the class  function __destruct() {    echo "The price of this furniture is {$this->price}.\n";     echo "The type of this furniture is {$this->type}.\n";  }}$sofa = new Furniture("50000", "Sofa");?>

OOPs_In_PHP_4

Inheritance 

Inheritance in PHP is one of the vital OOPs concepts in PHP, and can not be overviewed. Understanding inheritance is critical for understanding the whole point behind object-oriented programming. For instance, you are a human. Humans inherit from the class ‘Humans’ with characteristic features, such as walking, sitting, running, eating, and so on. The class ‘Humans’ inherits these characteristic features from the class ‘Mammal’ which makes the ‘Human' class a derived class of ‘Mammal’. This ‘Mammal’ class inherits its characteristic features from another class ‘Animal’ which makes the ’Mammal’ class a derived class of the class ‘Animal’ and makes the ‘Animal’ a base class.

One of the most astonishing features of inheritance is code reusability. This reusability also provides you with clean code, and the replication of code gets reduced to almost zero.

Reusing existing codes serves various advantages. It saves time, money, effort, and increases a program’s reliability. 

The syntax for declaring a base class to achieve inheritance in PHP:

class derived_class_name extends base_class_name {    // define member functions of    // the derived class here.}

The keyword extends is used to define a derived or child class in PHP.

Inheritance in PHP is of 3 types, which you will look at in this article, later on. 

  • Single Inheritance: Single inheritance is the most basic type of inheritance. In single inheritance, there is only one base class and one sub or derived class. The subclass is directly inherited from the base class.

The following example will illustrate single inheritance in PHP. 

<?php// base class named "Furniture"class Furniture {    var $cost = 1000;    public function printName($name) {        echo 'Class is: Furniture & name of furniture is: ' . $name . PHP_EOL;     } }// derived class named "Sofa"class Sofa extends Furniture {    public function printName($name) {        echo 'Class is: Sofa & name of furniture is: ' . $name . PHP_EOL;        // this class can access         // data member of its parent class.        echo 'Price is: ' . $this->cost . PHP_EOL;    }}$f = new Furniture();$s = new Sofa();$f->printName('Table'); $s->printName('Sofa'); ?>

OOPs_In_PHP_5.

  • Hierarchical Inheritance: As the name suggests, hierarchical inheritance shows a tree-like structure. There are many derived classes that are directly inherited from a base class. 

The following example will illustrate hierarchical inheritance in PHP. 

<?php// base class named "Furniture"class Furniture {    public function Furniture() {        echo 'This class is Furniture ' . PHP_EOL;     } }// derived class named "Sofa"class Sofa extends Furniture {  }// derived class named "Sofa"class Cupboard extends Furniture {  }// creating objects of // derived classes// "Sofa" and "Cupboard"$s = new Sofa();$c = new Cupboard();?>

OOPs_In_PHP_6.

  • Multilevel Inheritance: Multilevel Inheritance is the fourth type of inheritance that can be found in PHP. Multilevel inheritance can also be explained by a family tree. One base class exists and it inherits multiple subclasses. These subclasses (not every subclass necessarily) acts as base class and further inherits subclasses. This is just like a family having descendants over generations. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

The following example will illustrate hierarchical inheritance in PHP. 

<?php// base class named "Furniture"class Furniture {    public function totalCost() {        return  ' total furniture cost: 60000';    }}// derived class named "Table"// inherited form class "Furniture"class Table extends Furniture {    public function tableCost() {        return  ' table cost: 45000';    }}// derived class named "Study_Table"// inherited form class "Table"class Study_Table extends Table {    public function studyTableCost() {        return  ' study table cost: 60000';    }    public function priceList() {        echo '1. ' .$this->totalCost() . PHP_EOL;        echo '2. ' .$this->tableCost() . PHP_EOL;        echo '3. ' .$this->studyTableCost() . PHP_EOL;    }}// creating object of // the derived class$obj = new Study_Table();$obj->priceList();?>

OOPs_In_PHP_7

Inheritance is a splendid OOPs concept in PHP. Inheritance in PHP serves many advantages. There are several reasons why inheritance was introduced in OOPs. You will be exploring some of the major reasons behind the introduction of inheritance in PHP in this section:

  • One of the most astonishing reasons is that inheritance increases the relatability of the code to real-world scenarios drastically. 
  • Another reason is the idea of reusability. Code reusability ensures that a clean code is provided to the programmer. This also helps in the reduction of rewriting and serves a bug-free code, as the replication of the code gets reduced to almost zero with the help of reusability. Other advantages that can be achieved through reusability are time management, maintenance, and ease of extension. You can do manipulations and add some desired features to a class that already exists through inheritance. 
  • One more reason is the transitive nature of inheritance. Transitive nature implies that if two objects that are in succession show a pattern, then all the objects of that order must show the exact pattern.  For example, if a new class Tata Safari has been declared as a subclass of Car which itself is a subclass of Vehicle, then Tata Safari must also be a Vehicle i.e., inheritance is transitive in nature

Function Overloading

Function overloading takes place when you create two functions of the same name and these functions serve different purposes. Both functions should have strictly different arguments from each other. 

The following example will illustrate the function overloading concept in PHP.

<?phpclass Example{    public function __call($argument1, $argument2)    {          echo "I am being called using the object method '$argument1' "             . implode(', ', $argument2). "\n";    }    public static function __callStatic($argument1, $argument2)    {         echo "I am being called using the object method '$argument1' "             . implode(', ', $argument2). "\n";    }}$obj = new Example;$obj->overloadingExample('with the context of object');Example::overloadingExample('with the context of static');?>

OOPs_In_PHP_8

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Function Overriding 

Function overriding happens when your derived class and base class both contain a function having the same name. Both the functions should have the same number of arguments. The derived class inherits the member functions and data members from its base class. So to override a certain functionality, you need to perform function overriding. 

The following example will illustrate the function overriding OOPs concepts in PHP.

<?php    // Define the base class   class Example {      function printMessage() {         echo "\nExample class function declared final!";      }      function print() {         echo "\nI am the function of the class Example";      }   }   class childClass extends Example {      function print() {         echo "\nI am the function of the class childClass";      }   }   // create objects to call functions   $obj1 = new Example;   $obj1->print();   $obj1->printMessage();   $obj2 = new childClass;   $obj2->print();   $obj2->printMessage();?>

OOPs_In_PHP_9

Public, Private, and Protected Members 

The visibility mode (private or public or protected) in the definition of the derived class specifies whether the features of the base class are privately derived or publicly derived or protected derived. The visibility modes basically control the access-specifier to be for inheritable members of base-class, in the derived class.

  • Public Visibility Mode: Public Visibility mode gives the least privacy to the attributes of the base class. If the visibility mode is public, it means that the derived class can access the public and protected members of the base class but not the private members of the base class. 

The following example will illustrate the public visibility mode in PHP.

<?php// Define the base classclass Furniture {    public $price = "We have a fixed price of 50000";    function printMessage() {        echo $this->price;        echo PHP_EOL;    }}//  define the derived classesclass Sofa extends Furniture {    function print(){        echo $this->price;        echo PHP_EOL;    }}// create the object of the// derived class.$obj= new Sofa;// call the functionsecho $obj->price;echo PHP_EOL;$obj->printMessage();$obj->print();?>

OOPs_In_PHP_10

  • Private Visibility Mode: Private Visibility mode gives the most privacy to the attributes of the base class. If the visibility mode is private, that means the derived class can access the public and protected members of the base class privately. 

The following example will illustrate the private visibility mode in PHP.

<?php// Define the base classclass Furniture {    protected $price1 = 1000;    protected $price2 = 2000;       // Subtraction Function    function total()    {        echo $sum = $this->price1 + $this->price2;        echo PHP_EOL;    }   }// define the derived classesclass Sofa extends Furniture {    function printInvoice()     {        $tax = 100;        echo $sub = $this->price1 + $this->price2 + $tax;        echo PHP_EOL;    }}$obj= new Sofa;$obj->total();$obj->printInvoice();?>

OOPs_In_PHP_11.

  • Protected Visibility Mode: The protected visibility mode is somewhat between the public and private modes. If the visibility mode is protected, that means the derived class can access the public and protected members of the base class protectively. 

The following example will illustrate the protected visibility mode in PHP.

<?php// Define the base classclass Furniture {    private $price = "We have a fixed price of 50000";    private function show()    {        echo "This is private method of base class";    }}//  define the derived classesclass Sofa extends Furniture {    function printPrice()    {        echo $this->price;    }}// create the object of the// derived class$obj= new Sofa;// this line is trying to // call a private method.// this will throw error$obj->show();// this will also throw error$obj->printPrice();?>

OOPs_In_PHP_12

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Interfaces 

The interface lets you develop programs. You can create the interface in PHP by using the interface keyword. With the help of interfaces, you can also add public methods in your class without having to care much about the complexities and technicalities of how these methods can be implemented.

Syntax to define interfaces in PHP:

<?php  // syntax to define interface  // using the keyword "interface"  interface name_of_interface {    public function function_name_2();    public function function_name_1();  }?>

An interface can also be called the abstract method as the interface has only methods without the body or implementation. One of the major differences between interface and class is that only a single class can be derived from a base class but on the other hand a number of instances can be derived from a single class.

There is another important concept of concrete class in interfaces that can not be missed. Those classes that carry out interfaces are known as concrete classes. Concrete classes implement all the methods that have been defined in the interface. One thing to note here is that if you create two instances of the same name you will get an ambiguity error. 

The following example will illustrate the concept of interfaces in PHP.

<?phpinterface Furniture {  public function printPrice();  public function printItem();}class Sofa implements Furniture {  public function printPrice() {    echo "Price of Sofa is: 65000" . "\n";  }  public function printItem() {    echo "Other items are: Table and Cupboard". "\n";  }}$obj = new Sofa;$obj->printPrice();$obj->printItem();?>

OOPs_In_PHP_13

Advantages of Interfaces

  • Different classes can access the same methods irrespective of their hierarchical structure. You can achieve this without having to care about whether these classes are connected or not.
  • Unlike a class, interfaces can build multiple inheritance structures, as a class can inherit multiple interfaces.

Constants

Constants are the identifiers that do not change their value through the course of the code. You can declare constants so that their value can not be changed by mistake. 

Consider an example. You have created a function to find the area of a circle and you declare a constant pie with a value of 3.14. Now if you declare pie as a variable, its value could be changed later on anywhere in the function and that will give you the wrong area. In such cases, you use constants. The main difference between constant and variable is that the value of variables can be changed anytime, whereas you can not change a constant value once you define it.

In PHP, constants can be created by two types:

  • define(): define() is a function that is used to create constants in the class. Define takes three parameters:
    1. name
    2. value
    3. Case-sensitivity

Syntax

// Syntax to declare a constant // using define().define(constant_name, constant_value, case-insensitive)// case-sensitive parameter is// by default FALSE in  PHP.

The following example will illustrate the first method of declaring a constant variable  in PHP, using the define().

<?phpdefine("constVariable", "I am a constant variable", true);echo constVariable;?>

OOPs_In_PHP_14

  • const keyword: You can also declare a constant using the constant keyword. Unlike the define() function, yyou do not have to define case sensitivity, the const keyword is by default case sensitive.

The following example will illustrate the first method of declaring a constant variable in PHP, using the const keyword.

<?php      // define a class      class example      {          // declare a constant variable        // using the const keyword          const constVariable = "I am a constant variable";      }  // call the constant variable// using the scope resolution  echo example::constVariable;  ?>  

OOPs_In_PHP_15.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Abstract Class

An abstract class is one of the most exciting and important topics of the OOPs. A class is said to be an abstract class if it contains at least one abstract method. Abstract methods are the methods that do not contain a body. Abstract classes totally rely on the derived class to carry out their tasks.

An abstract class is created when you only have the method name but you are not certain how to write the code for the same. 

The following example will illustrate the working of the abstract classes in PHP.

<?php// define an abstract classabstract class Furniture {  public $name;  public function __construct($name) {    $this->name = $name;  }  // abstract method of the  // abstract class.  // It will be defined later in the   // child clases.  abstract public function printType() : string;}// Derived classes are defined nowclass Sofa extends Furniture {  public function printType() : string {    return "I am a $this->name!";  }}class Table extends Furniture {  public function printType() : string {    return "I am a $this->name!";  }}class Cupboard extends Furniture {  public function printType() : string {    return "I am a $this->name!";  }}// Creating instances of the// derived classes.$Sofa = new Sofa("Sofa");echo $Sofa->printType();echo PHP_EOL;$Table = new Table("Table");echo $Table->printType();echo PHP_EOL;$Cupboard = new Cupboard("Cupboard");echo $Cupboard->printType();echo PHP_EOL;?>

OOPs_In_PHP_16.

Static Keyword 

The static keyword is used to directly access without creating the objects.  Methods that are recognized as static methods can be accessed directly. Static functions are only used in relation to classes rather than objects. These functions are only allowed to access the methods that are considered static methods. To achieve this feat, you need to use the static keyword.

The static keyword is a vital keyword and serves important uses. Those methods that are considered to be static methods are easily accessible. So, they can be shared and used by various instances of the class.

The following example will illustrate the purpose of the static keyword with classes in PHP.

<?php// a test class to // illustrate the working of// the static keyword.class test {  // define a static function named   // myStaticFunction, using the   // "static" keyword.   public static function myStaticFunction() {    echo "I am a static function." . PHP_EOL;  }}// to call a static function,// there is no requirement of creating// an object.// a static function can be called by using// a "scope resolution" operator// i.e. ::test::myStaticFunction();?>

OOPs_In_PHP_17

Final Keyword 

The final keyword is a critical keyword in OOPs concepts in PHP and can be found in various programming languages such as Java. However, the final keyword serves different purposes in different languages. In PHP, the final keyword can be used with both classes and methods but act differently with both of them. 

In classes, you must use the final keyword whenever you want the inheritance out of the way, ie, to prevent inheritance in your class. Below is the example code displaying the use of the final keyword with class.

The following example will illustrate the purpose of the final keyword with classes in PHP. 

Note: This code will throw an error as you are trying to inherit a final class.

<?php   final class Furniture {      final function displayMessage() {         echo "I am a final class. You can not inherit my properties!";      }      function print() {         echo "I am the Furniture class function.";      }   }   class testClass extends Furniture {      function show() {         echo "I am the test class function.";      }   }   $obj = new testClass;   $obj->show();?>

OOPs_In_PHP_18

In methods, the final keyword can be used to avoid the issue caused in the case of method overriding. 

The following example will illustrate how a program works with and without the final keyword.

  • Without the final keyword (Will produce output, but cause method overriding)
<?php   class Furniture {      function printMessage() {         echo "I am the function of derived class.";      }   }   class testClass extends Furniture {      function printMessage() {         echo "I am the function of derived class.";      }   }   $ob = new testClass;   $ob->printMessage();?>

OOPs_In_PHP_19

  • With the final keyword (Will throw an error, to prevent method overriding)
<?php   class Furniture {      final function printMessage() {         echo "I am the function of derived class.";      }   }   class testClass extends Furniture {            function printMessage() {         echo "I am the function of derived class.";      }   }     $ob = new testClass;   $ob->printMessage();?>

OOPs_In_PHP_20

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Calling Parent Constructors 

The constructor of a parent class is another important OOP concept in PHP. The reason is that there might be situations when you want to use the constructor of a parent class in its child class, but to do that, you have to consider two situations that you might face while doing so.

  • When a constructor is already defined in the derived class.

In the case when the derived class already has a constructor defined in it, calling the parent’s class constructor can be made possible with the help of the scope resolution operator (i.e. the “::” operator).

The following example will illustrate the first situation of calling the parent class constructor in PHP.

<?php   class Furniture {      public function __construct(){         echo "I am the constructor of the parent class.\n";      }   }   class Sofa extends Furniture {      public function __construct(){        // call the constructor        // of the parent class        // using the :: operator         parent::__construct();         echo "I am the constructor of the derived class.\n";      }   }$obj = new Sofa();?>

OOPs_In_PHP_21

  • When the derived class does not have a constructor defined in it.

In the case when there is no constructor defined in the derived class, the constructor of its parent class will automatically be inherited by it directly. And when an instance of the derived class is created, the inherited constructor of the parent class will also be called.

The following example will illustrate the first situation of calling the parent class constructor in PHP.

<?php   class Furniture{      public function __construct(){         echo "This is the constructor of the parent class.";      }   }   class Sofa extends Furniture{   }   // When this object of the   // derived class is created,   // the constructor of the    // parent class inherited   // in the derived class   // will automatically   // be called.   $obj = new Sofa();?> 

OOPs_In_PHP_22.

Wrapping Up!

In this article, you learned about OOPs Concepts in PHP. You saw PHP and its object-oriented concepts in depth. Then, you dived deep into the constructors, destructors, and keywords used in PHP. Finally, you explored in detail what PHP is, and its various aspects. 

To get started with PHP, you can refer to this video.

Don’t just stop here. To learn MEAN stack development and to give yourself a chance to work for top tech giants, check out our course on Full Stack Developer - MERN Stack. In this course, you will learn some of the hottest skills like Node, Mongo, etc. that will help you to set your foot into professional web development. 

If you have any questions for us, please mention them in the comments section and we will have our experts answer them for you.

Happy Learning!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.