Classes & Objects in PHP

From the PHP cheat sheet · Object-Oriented PHP · verified Jul 2026

Classes & Objects

Basic class definition and object creation

php
class User {
    public string $name;
    private int $age;

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

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

// Create object
$user = new User('John', 30);
echo $user->greet();
💡 Constructor property promotion reduces boilerplate
⚡ Readonly properties ensure immutability
📌 Use visibility modifiers for encapsulation
🔥 Static properties/methods shared across all instances

More PHP tasks

Back to the full PHP cheat sheet