Introduction to Object-Oriented PHP: Classes and Objects Explained πŸš€

Introduction to Object-Oriented PHP: Classes and Objects Explained πŸš€

If you’re coding PHP without object-oriented programming (OOP), you’re missing out on a powerful way to organize and reuse code!

OOP makes your code cleaner, reusable, and scalableβ€”perfect for real-world applications like e-commerce websites, blog platforms, and APIs.

🎯 In this guide, you’ll learn:

βœ… What object-oriented programming is
βœ… How to create PHP classes and objects
βœ… How to use properties and methods
βœ… How to build a mini OOP-based project

Let’s dive in! πŸš€


1️⃣ What Is Object-Oriented Programming (OOP)?

OOP is a way of structuring code using classes and objects.

πŸ’‘ Think of a class as a blueprint (e.g., a Car).
πŸ’‘ An object is an instance of a class (e.g., a Toyota or a Tesla).


2️⃣ Creating a Class in PHP

Example: Defining a Simple Class

<?php
class Car {
    // Properties (variables)
    public $brand;
    public $color;

    // Constructor (Runs when an object is created)
    public function __construct($brand, $color) {
        $this->brand = $brand;
        $this->color = $color;
    }

    // Method (function inside a class)
    public function getDetails() {
        return "This is a $this->color $this->brand.";
    }
}

// Creating an object (instance of the class)
$myCar = new Car("Toyota", "Red");

// Output car details
echo $myCar->getDetails(); 
?>

πŸ”₯ What’s happening?
βœ… class Car {} defines the class.
βœ… Properties store data ($brand, $color).
βœ… A constructor (__construct) initializes objects.
βœ… Methods (like getDetails()) define behavior.


3️⃣ Understanding Class Properties and Methods

Example: Using Public and Private Properties

<?php
class User {
    public $name;
    private $email; // Private property (cannot be accessed outside the class)

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

    public function getEmail() {
        return "User email: " . $this->email;
    }
}

$user1 = new User("Zero Dev", "zero@zeroexp.dev");

echo $user1->name; // βœ… Works (public property)
echo $user1->getEmail(); // βœ… Works (accessing private property via a method)

// echo $user1->email; // ❌ Error (email is private)
?>

πŸ”₯ Why use private properties?
βœ… Encapsulation (hides sensitive data).
βœ… Restricts direct access to prevent accidental modification.


4️⃣ Using Getters and Setters

Instead of accessing properties directly, use getter and setter methods.

Example: Protecting Data with Getters/Setters

<?php
class BankAccount {
    private $balance = 0;

    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
            return "Deposited: $$amount";
        }
        return "Invalid amount!";
    }

    public function getBalance() {
        return "Current Balance: $$this->balance";
    }
}

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

πŸ”₯ Why use getters/setters?
βœ… Protects sensitive data
βœ… Validates input before modification


5️⃣ Inheritance: Reusing Code

Inheritance allows a class to inherit properties and methods from another class.

Example: Parent and Child Classes

<?php
class Animal {
    public $name;

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

    public function makeSound() {
        return "$this->name makes a sound.";
    }
}

// Dog class inherits from Animal
class Dog extends Animal {
    public function makeSound() {
        return "$this->name barks.";
    }
}

$dog = new Dog("Buddy");
echo $dog->makeSound(); // Output: Buddy barks.
?>

πŸ”₯ Why use inheritance?
βœ… Reduces code duplication
βœ… Allows better organization


6️⃣ Static Methods and Properties

Static properties and methods belong to the class itself, not individual objects.

Example: Using Static Methods

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

echo MathHelper::add(5, 10); // Output: 15
?>

πŸ”₯ When to use static methods?
βœ… For utility functions (e.g., MathHelper::add()).


🎯 Mini Project: OOP-Based User Management

Let’s build a real-world example using OOP.

1️⃣ User Class

<?php
class User {
    private $name;
    private $email;

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

    public function getDetails() {
        return "User: $this->name, Email: $this->email";
    }
}
?>

2️⃣ Admin Class (Extends User)

<?php
class Admin extends User {
    public function accessDashboard() {
        return "Admin $this->name has access to the dashboard.";
    }
}
?>

3️⃣ Testing the Classes

<?php
require "User.php";
require "Admin.php";

$user = new User("Zero Dev", "zero@zeroexp.dev");
$admin = new Admin("Admin User", "admin@zeroexp.dev");

echo $user->getDetails();
echo $admin->accessDashboard();
?>

πŸ”₯ What’s happening?
βœ… Encapsulated user data
βœ… Reused code with inheritance


πŸš€ Final Thoughts

Now you understand the core concepts of OOP in PHP!
βœ… Classes and Objects
βœ… Encapsulation (private/protected properties)
βœ… Inheritance for reusability
βœ… Static methods for utilities

πŸ‘‰ Next: Understanding PHP Inheritance and Interfaces

Happy coding! πŸŽ‰πŸš€

Leave a Reply