Learn PHP Β· 9/14

Object-Oriented Programming (OOP) Part 2: Advanced Concepts

13 min read

Course: PHP

Topic: Object-Oriented Programming (OOP) Part 2: Advanced Concepts

Hey there, welcome back! πŸ‘‹ You've got the basics of classes and objects down, which is awesome. Now, let's level up and explore some advanced OOP concepts in PHP that will make your code more powerful, reusable, and organized. We're going to dive into how classes can relate to each other in cool and efficient ways.


1. Inheritance: Passing Down Traits to Child Classes πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦

The Problem: Code Duplication

Imagine you're building a system to manage different types of vehicles. You might have a Car class and a Truck class. Both cars and trucks have a brand and a color, and both can start their engines. Without inheritance, you'd end up writing the same properties and methods in both classes.

php
class Car {
    public $brand;
    public $color;

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

    public function startEngine() {
        return "The {$this->color} {$this->brand} car's engine is starting.";
    }
}

class Truck {
    public $brand;
    public $color;
    public $payloadCapacity; // Specific to Truck

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

    public function startEngine() {
        return "The {$this->color} {$this->brand} truck's engine is starting.";
    }
}

See all that repeated code? If you need to change how the engine starts, you have to change it in two places. Now, imagine you add a Bus class. That's three places. This is a recipe for bugs and a headache for maintenance. πŸ€•

The Solution: Inheritance

Inheritance allows a class to acquire the properties and methods of another class. This concept models a real-world "is-a" relationship. A Car is a Vehicle, and a Truck is a Vehicle.

  • Parent Class (or Superclass): The class being inherited from (Vehicle).
  • Child Class (or Subclass): The class that inherits (Car, Truck).

PHP uses the extends keyword to establish this relationship.

Let's build a better system!

First, we create a generic Vehicle parent class with the common features.

php
// Parent class
class Vehicle {
    public $brand;
    public $color;

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

    public function startEngine() {
        return "The vehicle's engine is starting.";
    }
}

Now, the Car and Truck classes can inherit from Vehicle and add their own specific properties and methods.

php
// Child class
class Car extends Vehicle {
    public function drive() {
        return "The car is driving on the road.";
    }
}

// Another child class
class Truck extends Vehicle {
    public $payloadCapacity;

    public function __construct($brand, $color, $payloadCapacity) {
        // Call the parent constructor to set brand and color
        parent::__construct($brand, $color);
        $this->payloadCapacity = $payloadCapacity;
    }

    public function haul() {
        return "The truck is hauling a load of {$this->payloadCapacity} lbs.";
    }
}

// Let's see it in action
$myCar = new Car("Toyota", "Blue");
echo $myCar->startEngine(); // Inherited from Vehicle
// Output: The vehicle's engine is starting.

$myTruck = new Truck("Ford", "Red", 5000);
echo $myTruck->startEngine(); // Inherited from Vehicle
// Output: The vehicle's engine is starting.
echo $myTruck->haul(); // Specific to Truck
// Output: The truck is hauling a load of 5000 lbs.

What's happening here?

  • The Car and Truck classes automatically get the $brand, $color properties and the startEngine() method from Vehicle. No need to write them again!
  • The parent::__construct() line in the Truck class is important. It calls the constructor of the parent (Vehicle) class to handle the initialization of $brand and $color.

Method Overriding: Doing Things Your Own Way

What if a child class needs to perform an inherited action differently? This is called method overriding. You just redefine the method in the child class with the same name and parameters.

php
class Car extends Vehicle {
    // Overriding the parent's startEngine method
    public function startEngine() {
        return "The {$this->brand} car quietly purrs to life.";
    }
}

class Truck extends Vehicle {
    // Overriding the parent's startEngine method
    public function startEngine() {
        // You can even call the parent's method first if you want!
        $parentMessage = parent::startEngine();
        return $parentMessage . " The huge {$this->brand} truck roars to life!";
    }
}

$myCar = new Car("Tesla", "White");
echo $myCar->startEngine();
// Output: The Tesla car quietly purrs to life.

$myTruck = new Truck("Peterbilt", "Black");
echo $myTruck->startEngine();
// Output: The vehicle's engine is starting. The huge Peterbilt truck roars to life!

PHP is smart enough to know which method to call based on the object's type.

Under the Hood: When you call a method on an object, PHP first looks for that method inside the object's own class. If it doesn't find it, it walks up the inheritance chain to the parent class, and then the grandparent, and so on, until it finds the method or runs out of ancestors.

Access Modifiers: public, protected, and private

  • public: Accessible from anywhere.
  • private: Accessible only within the class that defined it. Child classes can't access private members of the parent.
  • protected: This is the key for inheritance! Protected members are accessible within the class itself and by its child classes.
php
class Vehicle {
    protected $engineStatus = "off"; // Child classes can access this

    public function startEngine() {
        $this->engineStatus = "on";
        return "Engine is now {$this->engineStatus}.";
    }
}

class Car extends Vehicle {
    public function getEngineStatus() {
        // This works because $engineStatus is protected
        return "The car's engine is currently {$this->engineStatus}.";
    }
}

$myCar = new Car("Honda", "Silver");
$myCar->startEngine();
echo $myCar->getEngineStatus(); // Output: The car's engine is currently on.
// echo $myCar->engineStatus; // This would cause a fatal error! Cannot access protected property.

Preventing Inheritance and Overrides: The final Keyword πŸ›‘

Sometimes, you want to stop other developers (or your future self) from extending a class or overriding a method. The final keyword is your "do not touch" sign.

  • final class: This class cannot be extended.
  • final public function: This method cannot be overridden by any child class.
php
final class SuperCar extends Car {
    // This class cannot be extended further.

    final public function engageHyperdrive() {
        // This specific method cannot be changed by any potential future child class
        // (though this class can't have children anyway because it's final).
        return "Entering ludicrous speed!";
    }
}

This is useful for creating core, stable classes in a framework where you don't want the fundamental behavior to be altered.

Funny Exaggeration: Without the final keyword, someone could extend your FinancialReport class, override the calculateTaxes() method to always return $0, and cause some... interesting accounting discrepancies. Use final to protect your most critical logic!


2. Interfaces: Enforcing Rules and Contracts πŸ“œ

The Problem: Lack of a Common Structure

Imagine you are building a payment processing system. You have different payment gateways: PayPal, Stripe, CreditCard. All of them need to be able to processPayment() and getTransactionStatus().

How do you guarantee that every payment gateway class you or your team creates will have these exact methods? A developer might forget, or name processPayment() something different like executePayment(). This would break your application wherever it expects a consistent method name.

The Solution: Interfaces

An interface is a contract. It defines a set of methods that a class must implement. It's like a blueprint for a class's public-facing behavior, but it doesn't provide any of the implementation (the code inside the methods).

You create an interface with the interface keyword and a class "signs the contract" using the implements keyword.

php
// The contract
interface PaymentGateway {
    public function processPayment(float $amount): bool;
    public function getTransactionId(): ?string;
}

// Stripe fulfills the contract
class Stripe implements PaymentGateway {
    private $transactionId;

    public function processPayment(float $amount): bool {
        // Logic to process payment with Stripe's API
        echo "Processing a payment of $$amount via Stripe.\n";
        $this->transactionId = "stripe_" . uniqid();
        return true; // Assume it was successful
    }

    public function getTransactionId(): ?string {
        return $this->transactionId;
    }
}

// PayPal also fulfills the contract
class PayPal implements PaymentGateway {
    private $transactionId;

    public function processPayment(float $amount): bool {
        // Logic to process payment with PayPal's API
        echo "Redirecting to PayPal to process $$amount.\n";
        $this->transactionId = "paypal_" . rand(1000, 9999);
        return true;
    }

    public function getTransactionId(): ?string {
        return $this->transactionId;
    }
}

If a class implements an interface, PHP will throw a fatal error unless that class defines all the methods listed in the interface with the exact same signature (name, parameters, and return type). This enforces a standard across different classes.

Why is this so useful in the industry?

It allows for polymorphism. This fancy word means you can use different classes that share the same interface interchangeably.

Let's say you have a function that processes an order. It doesn't need to know how the payment is processed, only that it can be processed.

php
function completeOrder(PaymentGateway $gateway, float $total) {
    echo "--- Starting Order ---\n";
    if ($gateway->processPayment($total)) {
        echo "Payment successful! Transaction ID: " . $gateway->getTransactionId() . "\n";
    } else {
        echo "Payment failed!\n";
    }
    echo "--- Order Finished ---\n\n";
}

// We can pass any object that implements the PaymentGateway interface
$stripeGateway = new Stripe();
$paypalGateway = new PayPal();

completeOrder($stripeGateway, 150.75);
completeOrder($paypalGateway, 89.99);

Output:

crmsh
--- Starting Order ---
Processing a payment of $150.75 via Stripe.
Payment successful! Transaction ID: stripe_65d3a...
--- Order Finished ---

--- Starting Order ---
Redirecting to PayPal to process $89.99.
Payment successful! Transaction ID: paypal_1234
--- Order Finished ---

The completeOrder function is decoupled from the specific implementation. You can add a new payment gateway tomorrow, and as long as it implements PaymentGateway, this function will work with it without any changes. That's incredibly powerful and flexible.

Interesting Fact: A class can inherit from only one parent class (single inheritance), but it can implement multiple interfaces! class MyClass extends ParentClass implements InterfaceA, InterfaceB { ... }. This allows a class to wear many hats and fit into different systems.


3. Abstract Classes: Creating Partial Blueprints πŸ—οΈ

The Problem: A Parent Class That Shouldn't Be Used Directly

Let's go back to our Vehicle example. The Vehicle class is a great concept, but does it make sense to create a generic "Vehicle" object? What is a vehicle? It's too general. You can't just go to a dealership and say "I'd like one vehicle, please." You buy a Car, a Truck, or a Motorcycle.

The Vehicle class exists to provide a common structure for its children, but it shouldn't be instantiated on its own. Furthermore, what if every vehicle must have a way to calculate its fuel efficiency, but the formula is different for each type?

The Solution: Abstract Classes

An abstract class is a class that cannot be instantiated on its own. It's a partial blueprint that is meant to be extended by other classes. It can contain regular methods and properties, but it can also contain abstract methods.

  • abstract class: A class that can't be turned into an object.
  • abstract function: A method that is declared but not implemented in the parent. The child class is required to provide the implementation.
php
abstract class Vehicle {
    public $brand;
    protected $isEngineOn = false;

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

    public function turnEngineOn() {
        $this->isEngineOn = true;
        echo "Engine is on.\n";
    }

    // This is an abstract method. It has no body {}.
    // Any child class MUST implement this method.
    abstract public function calculateFuelEfficiency(): float;
}

class Car extends Vehicle {
    private $miles;
    private $gallons;

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

    // We MUST implement the abstract method from the parent
    public function calculateFuelEfficiency(): float {
        return $this->miles / $this->gallons;
    }
}

class Truck extends Vehicle {
    private $distance;
    private $fuelUsed;
    private $loadWeight;

    // ... constructor ...

    public function calculateFuelEfficiency(): float {
        // A truck's efficiency might also depend on its load
        $baseMpg = $this->distance / $this->fuelUsed;
        return $baseMpg - ($this->loadWeight / 1000); // Fictional formula
    }
}

// $genericVehicle = new Vehicle("Generic"); // This will cause a FATAL ERROR!
// Cannot instantiate abstract class Vehicle

$myCar = new Car("Honda", 300, 10);
echo "My Honda's MPG: " . $myCar->calculateFuelEfficiency() . "\n";
// Output: My Honda's MPG: 30

Abstract Classes vs. Interfaces: The Big Question

This is a classic interview question! Here’s the simple breakdown:

Feature Abstract Class Interface
Purpose Share common code and enforce a common structure for related classes (is-a relationship). Enforce a "contract" of methods for unrelated classes (can-do relationship).
Methods Can have both regular methods (with code) and abstract methods (without code). Can ONLY have abstract public methods (no code).
Properties Can have properties (variables). Cannot have properties.
Inheritance A class can extend only one abstract class. A class can implement multiple interfaces.

Think of it this way:

  • Use an abstract class when you have a group of tightly related classes that share common functionality. Car and Truck are both types of Vehicles.
  • Use an interface when you want to define a capability that can be shared by completely different classes. A Stripe payment gateway and a User data object might both be Loggable (have a log() method), but they share nothing else in common.

4. Traits: Sharing Code Across Unrelated Classes 🀝

The Problem: Single Inheritance Limitation

We know PHP only allows a class to inherit from one parent. This is usually a good thing as it prevents a lot of complexity. But what if you have a piece of functionality that you want to share across several unrelated classes?

For example, you might have a logToFile() method. You could use this in your UserController, your PaymentProcessor, and your DatabaseConnector. These classes are not related. A UserController is not a DatabaseConnector. So, inheritance doesn't make sense. You could use an interface, but then you'd have to re-implement the logToFile() logic in every single class. That's code duplication all over again!

The Solution: Traits

A trait is a mechanism for code reuse in single-inheritance languages like PHP. It's like a "copy-paste" for a group of methods that can be injected into any class, without requiring inheritance.

You define a trait with the trait keyword and a class can use it with the use keyword.

php
// This is a Trait. It's a reusable bundle of methods.
trait Logger {
    public function log(string $message) {
        $timestamp = date("Y-m-d H:i:s");
        echo "[$timestamp] LOG: $message\n";
    }
}

class UserController {
    use Logger; // "Copy-paste" the Logger methods here

    public function createUser(string $name) {
        // ... logic to create a user ...
        $this->log("User '{$name}' created successfully.");
    }
}

class DatabaseConnector {
    use Logger; // Use the same trait in a completely different class

    public function connect() {
        // ... logic to connect to the DB ...
        $this->log("Database connection established.");
    }
}

$userController = new UserController();
$userController->createUser("Alice");
// Output: [2026-02-25 11:47:00] LOG: User 'Alice' created successfully.

$db = new DatabaseConnector();
$db->connect();
// Output: [2026-02-25 11:47:00] LOG: Database connection established.

The UserController and DatabaseConnector classes can now both use the log() method as if it were their own. No inheritance, no interface, just shared functionality.

Analogy Time: Imagine you're building different LEGO models: a car, a spaceship, and a castle. They are all fundamentally different. But what if you want all of them to have cool, blinking lights? Instead of redesigning the light-up brick for each model (code duplication), you just grab a pre-made "BlinkingLight" LEGO piece (the Trait) and stick it onto each model. A trait is that reusable component.

Traits solve the problem of needing to share methods horizontally across different class trees, giving you the best of both worlds: the structure of single inheritance and the flexibility of code sharing.


πŸ“š Extra Reading & References

Challenge

Challenge Instructions

Your task is to model a small employee hierarchy for a tech company using advanced PHP OOP principles. You will need to define a trait for logging, an interface for bonus calculations, an abstract class for the base employee, and several concrete classes for specific roles.

Requirements:

  1. Create a Logger Trait:

    • Define a trait named Logger.
    • It should contain one public method: logActivity(string $message). This method should return the string "Logging: " concatenated with the provided $message.
  2. Create a BonusEligible Interface:

    • Define an interface named BonusEligible.
    • It must declare one public method signature: calculateBonus(float $performanceFactor): float.
  3. Create an Employee Abstract Class:

    • Define an abstract class named Employee.
    • It must have two protected properties: $name and $employeeId.
    • It must have a public constructor that accepts a string $name and string $employeeId to initialize the properties.
    • It must have a public final method getEmployeeDetails() that returns a string formatted as: "ID: [employeeId], Name: [name]".
    • It must declare a public abstract method: calculateMonthlySalary(): float.
  4. Create a Manager Class:

    • This class must inherit from Employee.
    • It must implement the BonusEligible interface.
    • It must use the Logger trait.
    • It should have a private property: $baseSalary.
    • The constructor should accept $name, $employeeId, and a float $baseSalary, and correctly initialize all properties, including calling the parent constructor.
    • Implement calculateMonthlySalary() to return the $baseSalary.
    • Implement calculateBonus() to return the result of $baseSalary * $performanceFactor.
  5. Create a Developer Class:

    • This class must inherit from Employee.
    • It must implement the BonusEligible interface.
    • It must use the Logger trait.
    • It should have two private properties: $hourlyRate and $hoursWorked.
    • The constructor should accept $name, $employeeId, a float $hourlyRate, and a float $hoursWorked, calling the parent constructor as needed.
    • Implement calculateMonthlySalary() to return the result of $hourlyRate * $hoursWorked.
    • Implement calculateBonus() to return the result of ($hourlyRate * $hoursWorked) * $performanceFactor.
  6. Create a Designer Class:

    • This class must inherit from Employee.
    • It should not implement BonusEligible or use the Logger trait.
    • It should have a private property: $projectFee.
    • The constructor should accept $name, $employeeId, and a float $projectFee, calling the parent constructor.
    • Implement calculateMonthlySalary() to return the $projectFee.

Expected result

Your final code should consist of the complete definitions for the Logger trait, the BonusEligible interface, the Employee abstract class, and the three concrete classes: Manager, Developer, and Designer.

  • All classes must have the specified properties, constructors, and methods.
  • Inheritance (extends), interface implementation (implements), and trait usage (use) must be correctly applied as per the instructions.
  • Access modifiers (public, protected, private), as well as the abstract and final keywords, must be used correctly.
  • The code should be syntactically correct PHP, with all required methods from the abstract class and interface properly implemented in the child classes.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.