Lesson 14 of 20

Object-Oriented PHP

Classes and Objects

PHP supports full object-oriented programming with classes, objects, access modifiers, and constructors.

Example
<?php
class User {
    // Properties with types (PHP 7.4+)
    private string $name;
    private string $email;
    private int $age;

    // Constructor
    public function __construct(string $name, string $email, int $age) {
        $this->name = $name;
        $this->email = $email;
        $this->age = $age;
    }

    // Constructor promotion (PHP 8)
    // public function __construct(
    //     private string $name,
    //     private string $email,
    //     private int $age
    // ) {}

    // Methods
    public function greet(): string {
        return "Hello, I'm {$this->name}!";
    }

    // Getter
    public function getName(): string {
        return $this->name;
    }

    // Magic method
    public function __toString(): string {
        return "{$this->name} ({$this->email})";
    }
}

$user = new User('Alice', 'alice@example.com', 25);
echo $user->greet();
echo $user; // calls __toString
?>