PHP OOP Classes Interfaces Traits & Namespaces

Zaheer Ahmad 5 min read min read
Python
PHP OOP Classes Interfaces Traits & Namespaces

Introduction

PHP is a versatile language, widely used in Pakistan for web development. While procedural programming works for small scripts, real-world applications often require complex structures, which is where OOP in PHP comes into play.

By mastering PHP OOP, Pakistani developers can:

  • Organize code into reusable classes and objects.
  • Implement standard behaviors via interfaces.
  • Avoid code duplication using traits.
  • Prevent naming conflicts with namespaces.

This tutorial is designed for intermediate learners who have basic knowledge of PHP syntax, functions, and arrays.


Prerequisites

Before diving into PHP OOP, you should be familiar with:

  • Basic PHP syntax and variables.
  • Functions and loops in PHP.
  • Arrays (indexed and associative arrays).
  • Basic understanding of web applications.

If you are new to PHP, you can check out our PHP Tutorial for Beginners to strengthen your fundamentals.


Core Concepts & Explanation

Understanding PHP Classes

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the object will have. Think of a class as a “template” for real-world entities.

Example: PHP Class for a Student

<?php
class Student {
    public $name;
    public $age;
    public $city;

    // Constructor to initialize the object
    public function __construct($name, $age, $city) {
        $this->name = $name;
        $this->age = $age;
        $this->city = $city;
    }

    // Method to display student info
    public function getInfo() {
        return "Name: $this->name, Age: $this->age, City: $this->city";
    }
}

// Creating an object
$student1 = new Student("Ahmad", 21, "Lahore");
echo $student1->getInfo();
?>

Explanation line by line:

  1. class Student { ... } – Defines a class named Student.
  2. public $name; – Property accessible from outside the class.
  3. public function __construct(...){...} – Constructor initializes object properties.
  4. getInfo() – Method that returns student information.
  5. $student1 = new Student(...) – Creates a new object of the Student class.
  6. echo $student1->getInfo(); – Calls the method and prints the result.

PHP Interfaces: Defining Contracts

An interface defines a contract that classes must follow. Interfaces cannot contain properties or method implementations; they only declare methods.

<?php
interface PaymentGateway {
    public function pay($amount);
}

class JazzCash implements PaymentGateway {
    public function pay($amount) {
        return "Paid PKR $amount via JazzCash";
    }
}

$payment = new JazzCash();
echo $payment->pay(500);
?>

Explanation:

  • interface PaymentGateway – Declares the methods a class must implement.
  • class JazzCash implements PaymentGateway – Class adheres to the interface.
  • pay($amount) – Implements the interface method.

Use Case: Pakistani e-commerce websites can implement multiple payment gateways (JazzCash, EasyPaisa, Bank Transfer) using the same interface, ensuring consistent behavior.


PHP Abstract Classes: Partially Implemented Classes

Abstract classes are classes that cannot be instantiated directly and can contain both implemented and unimplemented methods.

<?php
abstract class Employee {
    public $name;
    public $salary;

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

    abstract public function calculateBonus();
}

class Developer extends Employee {
    public function calculateBonus() {
        return $this->salary * 0.10;
    }
}

$dev = new Developer("Fatima", 80000);
echo $dev->calculateBonus();
?>

Explanation:

  • abstract class Employee – Cannot create objects of Employee.
  • abstract public function calculateBonus(); – Must be implemented in child classes.
  • Developer – Extends Employee and provides a concrete implementation.

PHP Traits: Reusing Code Across Classes

Traits allow you to reuse methods across multiple classes without inheritance.

<?php
trait Logger {
    public function log($message) {
        echo "[LOG]: $message";
    }
}

class Order {
    use Logger;
    public function createOrder() {
        $this->log("Order created for Ali in Karachi");
    }
}

$order = new Order();
$order->createOrder();
?>

Explanation:

  • trait Logger – Defines reusable methods.
  • use Logger; – Imports trait into a class.
  • $order->createOrder(); – Calls trait method inside class method.

PHP Namespaces: Organizing Large Applications

Namespaces prevent class name conflicts in large applications.

<?php
namespace Lahore\Payments;

class JazzCash {
    public function pay() {
        return "Payment processed in Lahore";
    }
}

$payment = new \Lahore\Payments\JazzCash();
echo $payment->pay();
?>

Explanation:

  • namespace Lahore\Payments; – Defines a namespace.
  • \Lahore\Payments\JazzCash() – Fully qualified class name to prevent conflicts.
  • Use case: Large projects in Pakistan with multiple modules like Payment, User, and Orders can stay organized.

Practical Code Examples

Example 1: Student Management System

<?php
class Student {
    public $name;
    public $grade;

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

    public function display() {
        return "$this->name scored $this->grade in exams.";
    }
}

$student1 = new Student("Ali", "A+");
echo $student1->display();
?>

Explanation:

  • Useful for school portals in Islamabad or Lahore.
  • Each student object stores personal info and grades.

Example 2: Real-World Payment System

<?php
interface Gateway {
    public function processPayment($amount);
}

class EasyPaisa implements Gateway {
    public function processPayment($amount) {
        return "PKR $amount paid via EasyPaisa";
    }
}

class JazzCash implements Gateway {
    public function processPayment($amount) {
        return "PKR $amount paid via JazzCash";
    }
}

$payment1 = new EasyPaisa();
$payment2 = new JazzCash();

echo $payment1->processPayment(1200);
echo "\n";
echo $payment2->processPayment(1500);
?>
  • Each payment class follows the Gateway interface.
  • Demonstrates a real-life Pakistani e-commerce use case.

Common Mistakes & How to Avoid Them

Mistake 1: Confusing Interfaces and Abstract Classes

  • Problem: Trying to implement logic inside an interface.
  • Fix: Use abstract classes for partial implementations; interfaces only declare methods.
// WRONG
interface Payment {
    public function pay() {
        echo "Cannot implement here!";
    }
}

Mistake 2: Ignoring Namespaces in Large Projects

  • Problem: Class name conflicts.
  • Fix: Always define namespaces and import them using use.
namespace Karachi\Orders;

class Order {}

Practice Exercises

Exercise 1: Create a Teacher Class

Problem: Build a Teacher class with properties: name, subject, and city. Include a method to display info.

Solution:

<?php
class Teacher {
    public $name;
    public $subject;
    public $city;

    public function __construct($name, $subject, $city) {
        $this->name = $name;
        $this->subject = $subject;
        $this->city = $city;
    }

    public function getInfo() {
        return "$this->name teaches $this->subject in $this->city.";
    }
}

$teacher = new Teacher("Sana", "Math", "Islamabad");
echo $teacher->getInfo();
?>

Exercise 2: Implement Multiple Payment Gateways

Problem: Implement a Gateway interface and two classes (JazzCash and EasyPaisa). Each should process payments.

Solution: Refer to Example 2 above.


Frequently Asked Questions

What is PHP OOP?

PHP OOP is a way to structure PHP code around objects and classes. It improves code reusability, readability, and organization.

How do I create a class in PHP?

Use the class keyword followed by a name. Define properties and methods inside curly braces {}.

What is the difference between an interface and an abstract class?

An interface defines method contracts with no implementation, while an abstract class can include both implemented and unimplemented methods.

What are traits in PHP?

Traits are reusable methods that can be included in multiple classes, allowing code reuse without inheritance.

Why are namespaces important in PHP?

Namespaces prevent naming conflicts in large projects and help organize code logically.


Summary & Key Takeaways

  • Classes define blueprints for objects; objects store data and behavior.
  • Interfaces enforce contracts across multiple classes.
  • Abstract classes allow partial implementation of methods.
  • Traits help reuse code across unrelated classes.
  • Namespaces organize large projects and prevent conflicts.
  • Modern PHP (PHP 8+) offers improved type safety and OOP features.


This tutorial includes code blocks with line-by-line explanations, Pakistani real-world examples, practical exercises, and placeholders for images that visually enhance learning. It fully adheres to the ## H2 and ### H3 heading rules for theiqra.edu.pk’s TOC sidebar and SEO-rich structure.


If you want, I can also generate all the [IMAGE: prompt] visuals for this tutorial so it’s ready for publishing on theiqra.edu.pk.

Do you want me to do that next?

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad