PHP Intermediate

PHP Object-Oriented Programming (OOP)

CodingerWeb
CodingerWeb
20 views 50 min read

PHP Object-Oriented Programming (OOP)

Object-Oriented Programming is a programming paradigm that organizes code into classes and objects, making it more modular, reusable, and maintainable.

Classes and Objects

Classes are blueprints for creating objects:

<?php
// Define a class
class User {
    // Properties (attributes)
    public $name;
    public $email;
    private $password;
    protected $id;
    
    // Constructor - called when object is created
    public function __construct($name, $email, $password) {
        $this->name = $name;
        $this->email = $email;
        $this->password = password_hash($password, PASSWORD_DEFAULT);
        $this->id = uniqid();
    }
    
    // Methods (functions)
    public function getName() {
        return $this->name;
    }
    
    public function setName($name) {
        $this->name = $name;
    }
    
    public function verifyPassword($password) {
        return password_verify($password, $this->password);
    }
    
    public function getInfo() {
        return "User: " . $this->name . " (" . $this->email . ")";
    }
}

// Create objects (instances)
$user1 = new User("John Doe", "john@example.com", "password123");
$user2 = new User("Jane Smith", "jane@example.com", "secret456");

// Use objects
echo $user1->getName(); // John Doe
echo $user1->getInfo(); // User: John Doe (john@example.com)

$user1->setName("John Updated");
echo $user1->getName(); // John Updated
?>

Visibility (Access Modifiers)

Control access to properties and methods:

<?php
class BankAccount {
    public $accountNumber;    // Accessible everywhere
    private $balance;         // Only within this class
    protected $accountType;   // This class and subclasses
    
    public function __construct($accountNumber, $initialBalance) {
        $this->accountNumber = $accountNumber;
        $this->balance = $initialBalance;
        $this->accountType = "savings";
    }
    
    // Public method - accessible everywhere
    public function getBalance() {
        return $this->balance;
    }
    
    // Public method to modify private property
    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
            return true;
        }
        return false;
    }
    
    public function withdraw($amount) {
        if ($amount > 0 && $amount <= $this->balance) {
            $this->balance -= $amount;
            return true;
        }
        return false;
    }
    
    // Private method - only within this class
    private function calculateInterest() {
        return $this->balance * 0.02; // 2% interest
    }
    
    // Protected method - this class and subclasses
    protected function validateTransaction($amount) {
        return $amount > 0 && $amount <= 10000;
    }
}

$account = new BankAccount("12345", 1000);

echo $account->accountNumber; // Works - public
echo $account->getBalance();  // Works - public method

// echo $account->balance;     // Error - private property
// $account->calculateInterest(); // Error - private method
?>

Inheritance

Create new classes based on existing ones:

<?php
// Parent class (base class)
class Animal {
    protected $name;
    protected $species;
    
    public function __construct($name, $species) {
        $this->name = $name;
        $this->species = $species;
    }
    
    public function getName() {
        return $this->name;
    }
    
    public function makeSound() {
        return "Some generic animal sound";
    }
    
    public function getInfo() {
        return $this->name . " is a " . $this->species;
    }
}

// Child class (derived class)
class Dog extends Animal {
    private $breed;
    
    public function __construct($name, $breed) {
        // Call parent constructor
        parent::__construct($name, "Dog");
        $this->breed = $breed;
    }
    
    // Override parent method
    public function makeSound() {
        return "Woof! Woof!";
    }
    
    // Add new method
    public function fetch() {
        return $this->name . " is fetching the ball!";
    }
    
    // Override parent method with additional functionality
    public function getInfo() {
        return parent::getInfo() . " (" . $this->breed . " breed)";
    }
}

class Cat extends Animal {
    public function __construct($name) {
        parent::__construct($name, "Cat");
    }
    
    public function makeSound() {
        return "Meow!";
    }
    
    public function climb() {
        return $this->name . " is climbing a tree!";
    }
}

// Usage
$dog = new Dog("Buddy", "Golden Retriever");
$cat = new Cat("Whiskers");

echo $dog->getName();    // Buddy
echo $dog->makeSound();  // Woof! Woof!
echo $dog->fetch();      // Buddy is fetching the ball!
echo $dog->getInfo();    // Buddy is a Dog (Golden Retriever breed)

echo $cat->makeSound();  // Meow!
echo $cat->climb();      // Whiskers is climbing a tree!
?>

Abstract Classes and Methods

Define classes that cannot be instantiated directly:

<?php
// Abstract class - cannot be instantiated
abstract class Shape {
    protected $color;
    
    public function __construct($color) {
        $this->color = $color;
    }
    
    // Concrete method
    public function getColor() {
        return $this->color;
    }
    
    // Abstract method - must be implemented by child classes
    abstract public function calculateArea();
    abstract public function getPerimeter();
}

class Rectangle extends Shape {
    private $width;
    private $height;
    
    public function __construct($color, $width, $height) {
        parent::__construct($color);
        $this->width = $width;
        $this->height = $height;
    }
    
    // Must implement abstract methods
    public function calculateArea() {
        return $this->width * $this->height;
    }
    
    public function getPerimeter() {
        return 2 * ($this->width + $this->height);
    }
}

class Circle extends Shape {
    private $radius;
    
    public function __construct($color, $radius) {
        parent::__construct($color);
        $this->radius = $radius;
    }
    
    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
    
    public function getPerimeter() {
        return 2 * pi() * $this->radius;
    }
}

// Usage
$rectangle = new Rectangle("red", 10, 5);
$circle = new Circle("blue", 7);

echo "Rectangle area: " . $rectangle->calculateArea() . "
"; echo "Circle area: " . $circle->calculateArea() . "
"; echo "Rectangle perimeter: " . $rectangle->getPerimeter() . "
"; echo "Circle circumference: " . $circle->getPerimeter() . "
"; ?>

Practice Exercise

Create a Car class with:

  • Properties: brand, model, year, color
  • Methods: start(), stop(), getInfo()
  • Create multiple car objects and test the methods

Key Takeaways

  • Classes are blueprints for creating objects
  • Use $this to access object properties and methods
  • Constructors initialize object properties
  • Inheritance allows code reuse and extension