PHP OOPs


December 19, 2021, Learn eTutorial
1593

In this PHP tutorial, you will learn all about Object-Oriented Programming in PHP. We will discuss in detail Class, Objects, Constructors, Destructors, Access Modifiers, Inheritance, Abstract Class, Interface, Traits, Static Methods, Static Properties, and so on.

What is meant by Object-Oriented Programming in PHP?

Object-Oriented Programming (OOP) is a programming technique based on the concepts of classes and objects. Object-oriented means that we structure our program as a collection of various sorts of objects that have both data and behavior. In contrast to procedural programming, which focuses on developing procedures or functions that execute operations on data, object-oriented programming focuses on the construction of objects that include both data and functions. In object-oriented programming, the main concern is given to data security.

What are the advantages of Object-Oriented Programming in PHP?

  •   Object-Oriented Programming helps to provide programs with a clear modular structure.
  •   Object-Oriented Programming helps to follow the "don't repeat yourself" (DRY) philosophy, making your code much easier to maintain, alter, and debug.
  •  Object-Oriented Programming helps to execute the script much faster
  •  Object-Oriented Programming helps to enable the creation of more complex behavior programs with less script, a quicker development time, and a high degree of reusability.

The terms to know before we discuss the Object-Oriented Programming

  •        Class – 

    A class is a data type specified by the programmer that includes both local functions and local data. A class may be thought of as a template for creating several instances of the same kind (or class) of the object.

  •        Object – 

    An object is a single instance of a data structure described by a class. We can create a class once and then make multiple objects that belong to it. Objects are also referred to as instances.

  •        Member Variable – 

    Member variables are the variables that are declared within a class. This data will be hidden from the outside current class and may only be accessible through member functions. When an object is constructed, these variables are referred to as attributes of the object.

  •        Member function – 

    Member functions are functions that are specified within a class and are used to retrieve objects. The member functions are also called the methods.

  •        Inheritance – 

    It is termed inheritance when a class is defined by inheriting an existing behavior from a parent class. In this case, a child class will inherit all the parent class's member functions and variables.

  •        Parent class – 

    The parent class is that class that has been inherited by another class. The parent class is also called a base class or superclass.

  •        Child Class – 

    The child class is that class that inherits from another class. The child class is also called a subclass or derived class.

  •        Polymorphism – 

    Polymorphism is an object-oriented idea in which the same function may have several roles. For example, the function name will remain the same, but it will accept a different number of parameters and perform a new task.

  •        Overloading – 

    Overloading is a sort of polymorphism in which some or all operators have various implementations based on the types of arguments they receive. Similarly, functions with distinct implementations might be overloaded.

  •        Data Abstraction – 

    Data abstraction is any data format in which the implementation details are hidden (abstracted).

  •        Encapsulation – 

    Encapsulation is referring to a notion in which we encapsulate all of the data and member functions into a single object.

  •        Constructor – 

    The constructor refers to a particular sort of function that is called automatically whenever an object is formed from a class.

  •        Destructor – 

    The destructor is referred to as a sort of function that is called automatically if an item is removed or exits the scope

What is meant by class & objects in PHP?

The two basic components of object-oriented programming are classes and objects. A class is a self-contained, independent collection of variables and functions that work together to do one or more defined tasks, whereas objects are individual instances of a class. A class serves as a template or blueprint from which many different types of objects can be constructed. Individual objects inherit the same basic attributes and behaviors when formed, yet each object may have distinct values for specific properties.

How to define a class and object in PHP

To define a class in PHP we use the class keyword followed by the class name and pair of curly brackets “{}”
Syntax  


<?php
class classname {
  // code goes here...
}
?>

Example


<?php
class Students
{
    public $name;
    public $age;
    function set_detail($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    function get_details()
    {
        return "Name is " . $this->name . " and Age is " . $this->age;
    }
}
?>

The variables name and age inside the class Students are the Member Variables. The methods set_detail() and get_details() inside the class Students are the Member function.

Without objects, classes are insignificant. A class can be used to produce many objects. Each object has all of the properties and methods declared in the class, but their property values will differ.
To define an object of a class is created using the new keyword followed by the class name.
 

For example: we are using the same example


<?php
class Students
{
    public $name;
    public $age;
    function set_detail($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    function get_details()
    {
        return "Name is " . $this->name . " and Age is " . $this->age;
    }
}
$student1 = new Students();
$student2 = new Students();
$student1->set_detail('John', 19);
$student2->set_detail('Roy', 18);
echo $student1->get_details();
echo "\n";
echo $student2->get_details();
?>

Output:


Name is John and Age is 19
Name is Roy and Age is 18

The $this keyword is used to represent the current object. It will only be available inside the method only.

What is the use of instanceof keyword?

The instanceof keyword is used to check whether the object belongs to the class or not.
Example  

<?php
class Students
{
    public $name;
    public $age;
    function set_detail($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    function get_details()
    {
        return "Name is " . $this->name . " and Age is " . $this->age;
    }
}
$student = new Students();
var_dump($student1 instanceof Students);
?>

Output:


bool(true)

What is meant by the Constructor Function?

Constructor Functions are a kind of function that is called whenever an object is created. As a result, we make full use of this behavior by initializing numerous items using the constructor functions.
To define a constructor function in PHP we use the __construct() function. 
Example  

<?php
class Students
{
    public $name;
    public $age;
    function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    function get_details()
    {
        return "Name is " . $this->name . " and Age is " . $this->age;
    }
}
$student1 = new Students("John", 18);
echo $student1->get_details();
?>

Output:


Name is John and Age is 18

What is meant by the Destructor Function?

When an object is destroyed or the script is ended or terminated, a destructor is invoked. If you define a destructor function, PHP will call it at the conclusion of the script automatically.
To define a destructor function in PHP we use the __destruct() function. 
Example  

<?php
class Students
{
    public $name;
    public $age;
    function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    function __destruct()
    {
        echo "Name is " . $this->name . " and Age is " . $this->age;
    }
}
$student1 = new Students("John", 18);
?>

Output:


Name is John and Age is 18

What is meant by Inheritance?

The extended keyword allows classes to inherit the attributes and methods of another class. This extensibility method is known as inheritance. It is most likely the compelling reason for using the object-oriented programming approach.
To inherit a class, we use the extends keyword followed by the parent class name. 
Example  


<?php
class Students
{
    public $name;
    public $age;
    function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}
class DisplayStudents extends Students
{
    function get_details()
    {
        return "Name is " . $this->name . " and Age is " . $this->age;
    }
}
$student1 = new DisplayStudents('John', 19);
echo $student1->get_details();
?>

Output:


Name is John and Age is 19

What is meant by the Access Modifiers?

When dealing with classes, you can even use the access keywords to restrict access to its attributes and methods for more control. There are three visibility keywords (from most visible to least visible) that define how and from where properties and methods may be viewed and modified, they are public, protected, and private.

  •     Public property or method may be accessed from anywhere, both inside and outside the class. In PHP, this is the default visibility for all class members.
  •      protected property or method may only be accessible from within the class itself or from the child or inherited classes, that is, classes that extend that class.
  •     Private property or method is only available from within the class that defines it. Private properties or methods cannot be accessed by child or inherited classes.
     

Example


<?php
class Students
{
    public $roll_no;
    public $name;
    public $age;
    function __construct($roll_no, $name, $age)
    {
        $this->roll_no = $roll_no;
        $this->name = $name;
        $this->age = $age;
    }
}
class DisplayStudents extends Students
{
public function get_name()
    {
        echo "\nName is " . $this->name;
    }
    protected function get_age()
    {
        echo "\nAge is " . $this->age;
    }
    private function get_roll_no()
    {
        echo "RollName is " . $this->roll_no;
    }
}
$student1 = new DisplayStudents(101, 'John', 19);
$student1->get_name();
$student1->get_roll_no(); // it will throw an error since it is protected
$student1->get_age(); // it will throw an error since it is private
?>

What is meant by the Abstract Class?

When a parent class has a named method but requires its child class(es) to complete the responsibilities, this is referred to as an abstract class and method. A class that has at least one abstract method is referred to as an abstract class. An abstract method is one that has been declared but has not yet been implemented in code. When inheriting from an abstract class, the child class method must have the same name and the same or a less limited access modifier as the abstract class method. As a result, if the abstract method is protected, the child class method must also be protected or public, but not private. Furthermore, the type and quantity of needed arguments must be the same. However, the child classes may contain additional optional parameters.
To define an abstract class, we use the abstract keyword.
Example  


<?php
abstract class Languages
{
    public $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
    abstract public function intro(): string;
}
class Python extends Languages
{
    public function intro(): string
    {
        return "$this->name uses Python for Programming...";
    }
}
class PHP extends Languages
{
    public function intro(): string
    {
        return "$this->name uses PHP for Programming...";
    }
}
$John = new Python("John");
echo $John->intro();
echo "\n";
$Roy = new PHP("Roy");
echo $Roy->intro();
echo "\n";
?>

Output:


John uses Python for Programming...
Roy uses PHP for Programming...

What is meant by the Interfaces?

Interfaces are defined to provide implementers with common function names. Those interfaces can be implemented differently by different implementors depending on their needs. An interface is similar to a class, with the exception that it cannot include code. The names and parameters of methods can be defined by an interface, but not their contents.
To define an interface class, we use the interface keyword.
Example  


<?php
interface Greeting
{
    function sayHai();
}
class Welcome implements Greeting
{
    function sayHai()
    {
        echo "Hai! All Welcome to learnetutorials.com";
    }
}
$welcome = new Welcome();
$welcome->sayhai();
?>

Output:


Hai! All Welcome to learnetutorials.com

What is meant by the Traits?

PHP only allows single inheritance, which means that a child class may only inherit from one parent. So, what if a class requires numerous behaviors to be inherited? This issue is solved with OOP traits. Methods that may be utilized in various classes are declared using traits. Methods and abstract methods that may be used in various classes can be added to traits, and the methods can have any access modifier (public, private, or protected).
To define a Traits class, we use the trait keyword.
Example  


<?php
trait sayHai
{
    public function sayHai()
    {
        echo "Hai! All Welcome to learnetutorials.com... ";
    }
}
trait intro
{
    public function intro()
    {
        echo "We learn to code...";
    }
}
class Welcome
{
    use sayHai, intro;
}
$welcome = new Welcome();
$welcome->sayhai();
$welcome->intro();
?>

Output:


Hai! All Welcome to learnetutorials.comHai! All Welcome to learnetutorials.com... We learn to code...

What is meant by the Static Properties and Methods?

In addition to visibility, properties and methods can be marked as static, which makes them available without the requirement for a class instantiation. The scope resolution operator (::) may be used to access static properties and methods, as shown below: ClassName::$property and ClassName::method ().
Example  


<?php
class Welcome
{
    public static $sayHai = "Hai! all Welcome to learnetutorials.com...  ";
    public static function sayHello()
    {
        echo self::$sayHai;
    }
}
echo Welcome::$sayHai;
Welcome::sayHello();
?>

Output:


Hai! all Welcome to learnetutorials.com...  Hai! all Welcome to learnetutorials.com...