Lessons → PHP OOP → Lesson 2

Constructors & Destructors

PHP
⏱ 15 min read📖 IntermediateNot completed

A constructor is a special method that runs automatically when an object is created. A destructor runs when the object is destroyed.

Constructor (__construct)

PHP
<?php
class User {
    public string $name;
    public string $email;

    public function __construct(string $name, string $email) {
        $this->name  = $name;
        $this->email = $email;
        echo "User created: {$this->name}\n";
    }

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

$user = new User("John", "john@example.com");
// Automatically prints: User created: John

echo $user->greet();  // Hello, John!
?>

Constructor Property Promotion (PHP 8)

A shorter way to define and assign properties:

PHP 8
<?php
// Old way (verbose)
class Product {
    public string $name;
    public float $price;

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

// New way (PHP 8 - much cleaner!)
class Product {
    public function __construct(
        public string $name,
        public float $price,
        public int $stock = 0
    ) {}
}

$p = new Product("Laptop", 999.99, 50);
echo $p->name;   // Laptop
echo $p->price;  // 999.99
?>

Destructor (__destruct)

PHP
<?php
class DatabaseConnection {
    private $connection;

    public function __construct() {
        $this->connection = "Connected to DB";
        echo "DB connection opened\n";
    }

    public function __destruct() {
        $this->connection = null;
        echo "DB connection closed\n";
    }
}

$db = new DatabaseConnection();  // "DB connection opened"
// ... use the connection ...
// When script ends or $db goes out of scope:
// "DB connection closed" — destructor runs automatically
?>

Constructor with Validation

PHP
<?php
class Age {
    private int $value;

    public function __construct(int $age) {
        if ($age < 0 || $age > 150) {
            throw new InvalidArgumentException("Invalid age: $age");
        }
        $this->value = $age;
    }

    public function get(): int {
        return $this->value;
    }
}

$age = new Age(25);
echo $age->get();  // 25

// new Age(-5);  // Throws InvalidArgumentException
?>
💡
Laravel models use constructors too! Eloquent's Model class has a constructor that sets fillable attributes, casts, and more — this is why new User(['name' => 'John']) works in Laravel.
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take a quiz to reinforce what you learned.

Take Quiz →