PHP OOP Programming: A Complete Tutorial

PHP OOP Programming

A complex web application needs proper organization and maintenance to keep your code structured. This is where PHP Object-Oriented Programming (OOP) comes in. OOP lets you divide your code into reusable and easy-to-manage pieces.

We will cover the following topics in this tutorial:

  • What is object-oriented programming?
  • PHP OOP principles.
  • Basic OOP concepts in PHP.
  • Examples.

Let’s move on to what object-oriented programming is and how it works.

Understand Object-Oriented Programming (OOP) in PHP

Object-Oriented Programming (OOP) organizes code into objects. An object groups related data and functions. This makes code easier to manage and reuse.

OOP helps structure PHP applications better. Here is why it is useful:

  • Classes let you reuse code instead that you write classes again.
  • Organized code makes updates simpler.
  • Large projects become easier to manage.
  • Teams work when you use shared classes.
  • Encapsulation protects sensitive data.

OOP uses four main concepts:

  • Encapsulation.
  • Abstraction.
  • Inheritance.
  • Polymorphism.

Let’s take each one in-depth within the following section.

Principles of OOP in PHP

1- Encapsulation

Encapsulation controls how data inside an object is accessed and modified. A class can keep certain properties private.

It prevents direct changes from outside the class. Instead, it provides methods (getters and setters) to access or update the data. This prevents unintended modifications and keeps data secure.

class Member {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

$user = new Member();
$user->setName("FlatCoding Member Name");
echo $user->getName(); 

Output:

FlatCoding Member Name

The $name property stays private. Direct access is blocked. So, data stays controlled and secure.

2- Abstraction

Abstraction simplifies code and hides unnecessary details. A class can provide only the essential methods, and it keeps internal workings hidden. This reduces complexity.

For example:

abstract class Vehicle {
    abstract public function startEngine();
    
    public function stopEngine() {
        echo "Engine stopped";
    }
}

class Car extends Vehicle {
    public function startEngine() {
        echo "Car engine started";
    }
}

$car = new Car();
$car->startEngine(); 
$car->stopEngine(); 

Here is the output:

Car engine started
Engine stopped

The Vehicle defines a common structure, but Car provides specific behavior. The user does not need to know how the engine starts internally, just how to call the method.

3-Inheritance

Inheritance lets one class (child class) take properties and methods from another class (parent class).

This avoids duplicate code and makes changes easier. The child class can also override methods from the parent class to change behavior.

For Example:

class Animal {
    public function makeSound() {
        echo "Some sound";
    }
}

class Dog extends Animal {
    public function makeSound() {
        echo "Bark";
    }
}

$dog = new Dog();
$dog->makeSound();  

The output:

Bark

The Dog class inherits from Animal. But overrides the makeSound method. This lets it customize behavior while still being part of the Animal class.

4-Polymorphism

Polymorphism allows multiple classes to use the same method name but implement different behaviors. This makes code more scalable.

For example:

interface Shape {
    public function getArea();
}

class Circle implements Shape {
    private $radius;

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

    public function getArea() {
        return pi() * $this->radius * $this->radius;
    }
}

class Rectangle implements Shape {
    private $width;
    private $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function getArea() {
        return $this->width * $this->height;
    }
}

$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);

echo $circle->getArea();
echo $rectangle->getArea(); 

The output:

78.539816339745
24

In the following section, we will cover in-depth OOP concepts in PHP.

Basic OOP Concepts in PHP

Below are the core concepts you need to understand.

Classes and Objects

A class is a template that allows you to make objects. An object is a copy of a class. A class sets the variables and functions that its objects will use.

For example:

class Motorcycle {
    public $brand;

    public function ride() {
        echo "Riding a " . $this->brand;
    }
}

$bike1 = new Motorcycle();
$bike1->brand = "Harley-Davidson";
$bike1->ride(); 

The output:

Riding a Harley-Davidson

The Motorcycle class defines a property ($brand) and a method (ride). The $bike1 object is created from this class.

Properties and Methods

Properties store data inside a class and methods to perform actions. Methods can access and modify properties.

For example:

class Person {
    public $name;

    public function sayHello() {
        echo "Hello, my name is " . $this->name;
    }
}

$person = new Person();
$person->name = "Montasser";
$person->sayHello();  

The output:

Hello, my name is Montasser

The Person class has a property ($name) and a method (sayHello). The method uses $this->name to access the object’s data.

Access modifiers

Access modifiers control how properties and methods can be accessed.

  • Public: Accessible from anywhere.
  • Private: Accessible only within the class.
  • Protected: Accessible within the class and subclasses.

Here is an example:

class BankAccount {
    private $balance = 1000;

    public function getBalance() {
        return $this->balance;
    }
}

$account = new BankAccount();
echo $account->getBalance(); 

The output:

1000

The $balance is private, so direct access is blocked. The getBalance method allows controlled access.

Constructors and Destructors

A constructor runs when an object is created. A destructor runs when an object is no longer needed.

Example:

class FlatCodingUser {
    public function __construct() {
        echo "User of flatcoding.com created";
    }

    public function __destruct() {
        echo "User of flatcoding.com deleted";
    }
}

$user = new FlatCodingUser(); 

Output:

User of flatcoding.com created
User of flatcoding.com deleted

The constructor initializes the object, and the destructor cleans up resources.

Static Properties and Methods

Static properties and static methods belong to the class, not to an instance. You call them when you use ClassName::methodName().

Example:

class MathHelper {
    public static function add($a, $b) {
        return $a + $b;
    }
}

echo MathHelper::add(5, 3); 

Output:

8

The add the method is static, so you do not need to create an object to use it.

Namespaces in PHP OOP

Namespaces prevent name conflicts when you use multiple classes with the same name.

namespace App\Models;

class FlatCodingUser {
    public function getInfo() {
        echo "This info for user of FlatCoding.com";
    }
}

 
$user = new \App\Models\FlatCodingUser();
$user->getInfo();

The output:

This info for user of FlatCoding.com

The App\Models namespace keeps the FlatCodingUser class is separate from other classes with the same name.

Traits in PHP

Traits allow code reuse in multiple classes without inheritance.

For example:

trait Logger {
    public function log($message) {
        echo "Log: " . $message;
    }
}

class Order {
    use Logger;
}

$order = new Order();
$order->log("Order placed");  

The output:

Log: Order placed

The Logger trait provides a log method that any class can use.

Exception Handling in PHP OOP Programming

It lets you manage errors and does not need the script to stop.

Here is an example:

class Machine {
    public function operate($speed, $power) {
        if ($power == 0) {
            throw new Exception("Machine cannot run without power");
        }
        return "Machine running at " . $speed . " speed.";
    }
}

try {
    $machine = new Machine();
    echo $machine->operate(100, 0);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} 

The output:

Error: Machine cannot run without power

The try block runs the code, and the catch block catches errors if they happen. Instead of stopping the script it shows the error message.

Wrapping Up

You learned the basics of Object-Oriented Programming (OOP) in PHP and how it helps structure code for better reusability and organization. You also explored key OOP principles and how they work in PHP.

Here is a quick recap:

  • OOP concepts let you structure code with classes and objects. Also lets you control properties and methods.
  • Encapsulation restricts direct access to data inside a class.
  • Abstraction hides unnecessary details and shows only what is needed.
  • Inheritance lets one class reuse another class’s properties and methods.
  • Polymorphism allows different classes to use the same method in different ways.
  • Access modifiers control where properties and methods can be used.
  • Constructors and destructors handle setup and cleanup when you use objects.
  • Static properties and methods belong to a class instead of an object.
  • Namespaces prevent conflicts when classes have the same name.
  • Traits let multiple classes share code without using inheritance.
  • Exception handling catches errors and prevents the script from stopping.

FAQ’s

What is Object-Oriented Programming (OOP) in PHP?

OOP in PHP organizes code into objects that group related data and functions. This makes code easier to manage and reuse.

Why use OOP in PHP?

OOP helps structure applications better. It allows code reuse, makes updates easier, improves project organization, and helps teams work efficiently with shared classes.

What are the main principles of OOP in PHP?

OOP uses four main principles:
  • Encapsulation restricts direct access to data.
  • Abstraction hides complex details and shows only necessary parts.
  • Inheritance allows a class to use another class’s properties and methods.
  • Polymorphism lets different classes use the same method in different ways.

What is encapsulation in PHP OOP?

Encapsulation protects data inside a class by making properties private and allowing controlled access through methods.

How does abstraction work in PHP?

Abstraction hides the internal details of a class and provides only the necessary functions. This reduces complexity and makes code easier to use.

What is inheritance in PHP OOP?

Inheritance allows one class (child class) to reuse properties and methods from another class (parent class). This avoids code duplication and makes changes easier.

What is polymorphism in PHP?

Polymorphism lets multiple classes use the same method name while implementing different behaviors. This makes code flexible and scalable.

How does exception handling work in PHP OOP?

Exception handling catches errors using try and catch blocks. Instead of stopping the script, it handles errors and shows messages to prevent crashes.
Previous Article

Inheritance in PHP: Share Code from Class to Class & Examples

Next Article

PHP Null: How to Assign and Check for Null Values

Write a Comment

Leave a Comment

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

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.