PHP Part 9: Object-oriented Programming In PHP (OOP Pillars)

PHP Part 9: Object-oriented Programming In PHP (OOP Pillars)


Please Subscribe Youtube| Like Facebook | Follow Twitter

Object-Oriented Programming (OOP Pillars) In PHP

In this article, we will provide a detailed overview of Object-Oriented Programming In PHP (OOP Pillars) and provide examples of how they are used in PHP programming.

The Pillars of Object-Oriented Programming

OOP is built upon four key pillars: encapsulation, inheritance, polymorphism, and abstraction. In this article we explore them as in previous article we explored classes and objects.

Encapsulation

Encapsulation in PHP is a fundamental concept of object-oriented programming that involves bundling data and methods within a class and controlling their access using access modifiers. The access modifiers in PHP are:

Public: Allows unrestricted access to the class members from anywhere, both inside and outside the class.

Private: Restricts access to the class members only within the class itself. They cannot be accessed from outside the class or even from derived classes.

Protected: Allows access to the class members within the class itself and its derived classes.

Here’s an example of encapsulation in PHP:

<?php
class Car {
    private $model;
    private $year;

    public function setModel($model) {
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }

    public function setYear($year) {
        $this->year = $year;
    }

    public function getYear() {
        return $this->year;
    }
}

$car = new Car();
$car->setModel("Toyota Camry");
$car->setYear(2022);

echo "Model: " . $car->getModel() . "\n";
echo "Year: " . $car->getYear();

?>

Output

Model: Toyota Camry
Year: 2022

In the example above, the Car class has private properties $model and $year. These properties can only be accessed and modified using the public setter and getter methods (setModel(), getModel(), setYear(), and getYear()).

By encapsulating the properties, we ensure that they are accessed and modified through defined methods, allowing us to maintain control over how the properties are manipulated. Additionally, it provides data hiding, which prevents direct access to the internal state of the object and enhances the security and integrity of the class.

Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. In PHP, inheritance is achieved using the keyword extends. It enables code reuse, promotes modularity, and supports the hierarchical organization of classes.

Here’s a example that demonstrates inheritance in PHP:

<?php
/**
 * The Vehicle class represents a generic vehicle.
 */
class Vehicle {
    protected $brand;
    protected $color;

    public function __construct($brand, $color) {
        $this->brand = $brand;
        $this->color = $color;
    }

    public function drive() {
        return "The $this->brand is driving.";
    }
}

/**
 * The Car class extends the Vehicle class and adds specific car functionality.
 */
class Car extends Vehicle {
    private $numDoors;

    public function __construct($brand, $color, $numDoors) {
        parent::__construct($brand, $color);
        $this->numDoors = $numDoors;
    }

    public function getInfo() {
        return "This $this->color $this->brand has $this->numDoors doors.";
    }
}

// Create an instance of the Car class
$car = new Car("Toyota", "Blue", 4);

// Output the information about the car
echo $car->getInfo() . "\n";

// Drive the car
echo $car->drive();
?>

Output

This Blue Toyota has 4 doors.
The Toyota is driving.

In the example above, we have two classes: Vehicle and Car. The Vehicle class is the base or parent class, while the Car class is the derived or child class that extends the Vehicle class.

The Vehicle class has two protected properties, $brand and $color, along with a constructor that sets their values. It also has a drive() method that returns a basic driving message.

The Car class extends the Vehicle class using the extends keyword. It introduces an additional private property, $numDoors, and a constructor that sets all three properties using the parent class’s constructor through the parent::__construct() call. The Car class also defines its own getInfo() method to retrieve information specific to a car.

In the main part of the code, we create an instance of the Car class, passing the brand, color, and number of doors as parameters. We then call the getInfo() method to retrieve the car’s information and the drive() method to simulate driving the car.

Inheritance allows the Car class to inherit the properties and methods of the Vehicle class, providing code reusability and allowing the Car class to extend and specialize the functionality defined in the base class.

Parent keyword

parent keyword is used to refer to the parent class within a child class. It allows the child class to access and invoke methods or properties of the parent class

<?php
class Vehicle {
    protected $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function startEngine() {
        return "The engine of the $this->brand is starting.";
    }
}

class Car extends Vehicle {
    public function startEngine() {
        $engineStartMessage = parent::startEngine();
        return $engineStartMessage . " It's a car engine.";
    }
}

$car = new Car("Toyota");
echo $car->startEngine();
?>

Output

The engine of the Toyota is starting. It's a car engine.

In this example, we have two classes: Vehicle and Car. The Vehicle class has a protected property $brand and a method startEngine() that returns a generic engine start message for a vehicle.

The Car class extends the Vehicle class and overrides the startEngine() method. Inside the startEngine() method of the Car class, the parent::startEngine() call invokes the startEngine() method of the parent class. The result is then concatenated with the specific car engine message.

When we create an instance of the Car class and call the startEngine() method, it will output: “The engine of the Toyota is starting. It’s a car engine.” This demonstrates how the parent keyword allows the child class to invoke and extend the behavior of the parent class’s method.

By utilizing the parent keyword, the child class can access the methods or properties of the parent class and enhance or modify their functionality to fit the specific needs of the child class.

Polymorphism

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common parent class or interface. It provides flexibility and extensibility by enabling objects to be used interchangeably and exhibit different behaviors based on their actual class at runtime.

In PHP, polymorphism can be achieved through method overriding and type hinting. Method overriding occurs when a subclass provides its own implementation of a method that is already defined in its parent class. This allows the subclass to customize the behavior of the inherited method while maintaining the same method signature.

Unlike some other programming languages, such as Java, PHP does not natively support method overloading based on the number or types of arguments.

Here’s an example code snippet illustrating polymorphism (method overriding) in PHP:

<?php
class Animal {
    public function makeSound() {
        return "The animal makes a sound.";
    }
}

class Dog extends Animal {
    public function makeSound() {
        return "Woof!";
    }
}

class Cat extends Animal {
    public function makeSound() {
        return "Meow!";
    }
}

// Function that works with any Animal object
function animalSound(Animal $animal) {
    return $animal->makeSound();
}

$animal1 = new Animal();
$animal2 = new Dog();
$animal3 = new Cat();

echo animalSound($animal1); // Output: The animal makes a sound.
echo animalSound($animal2); // Output: Woof!
echo animalSound($animal3); // Output: Meow!

?>

Output

The animal makes a sound.
Woof!
Meow!

In the example above, we have an Animal class with a makeSound() method. The Dog and Cat classes extend the Animal class and override the makeSound() method with their own implementations.

The animalSound() function demonstrates polymorphism by accepting an Animal object as a parameter. This function can work with any object that is an instance of the Animal class or its subclasses (Dog or Cat), as they all share a common parent class.

When we call the animalSound() function with different objects, it invokes the appropriate makeSound() method based on the actual class of the object, returning the corresponding sound.

Polymorphism allows for code reusability and flexibility, as you can write functions or methods that operate on a common interface or superclass, and they can seamlessly work with different objects that inherit from that interface or superclass.

Abstraction

Abstraction is a crucial concept in object-oriented programming (OOP) that allows you to create classes and objects with generalized characteristics, hiding the complex implementation details from the users. It focuses on defining the essential properties and behaviors of an object without specifying how they are implemented.

In PHP, abstraction can be achieved through abstract classes and interfaces. Let’s explore each of them:

Abstract Class

An abstract class serves as a blueprint for other classes and cannot be instantiated directly. It can contain a combination of regular methods with implementations and abstract methods without implementations. Abstract methods act as placeholders that must be implemented by the classes that extend the abstract class. Abstract classes provide a way to define common functionality while allowing subclasses to provide specific implementations.

<?php
abstract class Vehicle {
    protected $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    abstract public function startEngine();
}

class Car extends Vehicle {
    public function startEngine() {
        return "The car engine is starting.";
    }
}

$car = new Car("Toyota");
echo $car->startEngine(); // Output: The car engine is starting.
?>

Output

The car engine is starting.

In the example above, Vehicle is an abstract class with an abstract method startEngine(). The Car class extends the Vehicle class and provides the implementation for the startEngine() method. Note that the abstract method in the abstract class does not contain any implementation code.

Interface

An interface is a contract that defines a set of methods that a class must implement. It specifies the method names, parameters, and return types, but not the implementations. Multiple classes can implement the same interface, providing their own unique implementations. Interfaces allow for class-to-class interaction and help achieve loose coupling between classes.

<?php
interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound() {
        return "Woof!";
    }
}

class Cat implements Animal {
    public function makeSound() {
        return "Meow!";
    }
}

$dog = new Dog();
echo $dog->makeSound(); // Output: Woof!

$cat = new Cat();
echo $cat->makeSound(); // Output: Meow!
?>

Output

Woof!
Meow!

In the above example, we have an Animal interface that defines a single method makeSound(). The Dog and Cat classes implement the Animal interface and provide their own implementations for the makeSound() method.

Interfaces allow objects of different classes to be treated interchangeably, as long as they implement the same interface. This promotes code flexibility and scalability.

To summarize, abstraction, abstract classes, and interfaces are powerful tools in PHP that promote code modularity, reusability, and flexibility. Abstraction helps in building generalized classes, while abstract classes and interfaces provide mechanisms for defining contracts and enforcing implementation rules.

Differences between an abstract class and an interface in PHP

TermAbstract ClassInterface
DefinitionA class that cannot be instantiated and may contain implementations and abstract methods.A contract that defines a set of methods that a class must implement.
InstantiationCannot be instantiated directly.Cannot be instantiated directly.
InheritanceCan extend only one abstract or concrete class.Can implement multiple interfaces.
Method DefinitionsCan contain both implemented methods and abstract methods.Contains method signatures only, without any implementations.
Method ImplementationAbstract methods must be implemented by the extending class.All methods defined in the interface must be implemented.
Access ModifiersCan have methods with public, protected, or private access modifiers.Methods are implicitly public in the interface.
PropertiesCan have properties with any access modifiers.Cannot have properties.
Common Use CaseUsed when creating a base class with some common functionality.Used when defining a contract that multiple classes must adhere to.

Conclusion

Encapsulation, inheritance, polymorphism, and abstraction are four fundamental concepts in PHP object-oriented programming. Together, they provide a powerful and flexible foundation for creating modular, maintainable, and extensible code.

PHP Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *