<?php OOP: Zero to Hero Chapter 05 of 20

Chapter 05 ยท OOP Foundations

Constructors

In the last chapter, creating a student took four lines: make it, set the name, set the program, set the balance. Real developers do it in one line โ€” thanks to a special method called the constructor.

The problem

$s = new Student();
$s->name = "Chanda";
$s->program = "BSc Computing";
$s->balance = 5000;

Annoying to type โ€” and dangerous. What if you forget to set the name? You'd have a half-built "ghost student" wandering through your program, causing errors later. We want a rule: a student cannot exist without a name.

๐ŸŽ‚
Real-world analogy

A constructor is like the registration desk on a student's first day. Before anyone becomes a student, they must pass the desk and hand over their details: full name, programme, fees. No details, no admission. The constructor is that desk โ€” it runs automatically the moment an object is born, and it can demand information.

Meet __construct

A constructor is just a method with the special name __construct (two underscores). PHP calls it automatically whenever you say new:

<?php
class Student {
    public string $name;
    public string $program;
    public float $balance;

    public function __construct(string $name, string $program, float $balance) {
        $this->name    = $name;
        $this->program = $program;
        $this->balance = $balance;
        echo "($name has been registered!)<br>";
    }

    public function introduce(): string {
        return "I am $this->name, studying $this->program.";
    }
}

// Now creating a student is ONE line:
$s1 = new Student("Chanda", "BSc Computing", 5000);
$s2 = new Student("Mutinta", "LLB", 7200);

echo $s1->introduce();
(Chanda has been registered!) (Mutinta has been registered!) I am Chanda, studying BSc Computing.

Follow the journey of the word "Chanda":

  1. new Student("Chanda", ...) โ€” you hand "Chanda" to the registration desk.
  2. It lands in the parameter $name inside __construct.
  3. $this->name = $name; โ€” "put the name I was given into my own name property." Left side: the object's permanent property. Right side: the temporary parameter.
Note

Now that the constructor guarantees values, we removed the = "" defaults from the properties. And if you try new Student() with no details, PHP immediately raises an error โ€” our "no details, no admission" rule is enforced by the language itself. That's protection we never had with arrays.

Default values โ€” optional details

Constructor parameters can have defaults, just like normal functions:

class Student {
    public function __construct(
        public string $name,
        public string $program,
        public float $balance = 0    // optional; 0 if not provided
    ) {}
}

$a = new Student("Bwalya", "BBA");          // balance becomes 0
$b = new Student("Thandiwe", "LLB", 2500);  // balance is 2500

Wait โ€” did you notice something amazing in that example? Look closer...

Promoted properties โ€” the modern shortcut

Since PHP 8, you can declare properties directly inside the constructor's brackets by adding public (or private) before each parameter. PHP then creates the property and assigns the value for you. These two classes are identical:

// The long, classic way
class Course {
    public string $code;
    public string $title;

    public function __construct(string $code, string $title) {
        $this->code  = $code;
        $this->title = $title;
    }
}

// The modern shortcut โ€” "constructor property promotion"
class Course {
    public function __construct(
        public string $code,
        public string $title
    ) {}
}

Both let you write new Course("COMP101", "Intro to Programming"). You will meet both styles in real projects, so learn to read both. In this course we'll mostly use the modern shortcut because it's shorter and clearer.

Constructors can do work, not just store

The registration desk doesn't only file your form โ€” it can also compute things, check rules, and prepare the object for life:

class Invoice {
    public string $number;
    public float $total;

    public function __construct(public string $studentName, public float $amount) {
        $this->total  = $amount * 1.16;                    // add 16% VAT automatically
        $this->number = "INV-" . strtoupper(uniqid());     // generate a unique invoice number
    }
}

$inv = new Invoice("Chanda", 1000);
echo "$inv->number for $inv->studentName: K" . number_format($inv->total, 2);
INV-6717B2C41F0A3 for Chanda: K1,160.00

__destruct โ€” the goodbye method

The rarely-used twin of the constructor: __destruct() runs automatically when an object is destroyed (usually when the script ends). It's occasionally used for cleanup, like closing files. You mostly just need to know it exists:

class Visitor {
    public function __construct(public string $name) {
        echo "$this->name entered.<br>";
    }
    public function __destruct() {
        echo "$this->name left. Goodbye!<br>";
    }
}

$v = new Visitor("Chanda");
echo "...doing some work...<br>";
Chanda entered. ...doing some work... Chanda left. Goodbye!
โœ๏ธ Try it yourself

Create a class Book using promoted properties: $title, $author, and $pages with a default of 100. Add a method summary() returning "1984 by George Orwell (328 pages)" style text. Create two books โ€” one using the default pages โ€” and print both summaries.

Show solution
<?php
class Book {
    public function __construct(
        public string $title,
        public string $author,
        public int $pages = 100
    ) {}

    public function summary(): string {
        return "$this->title by $this->author ($this->pages pages)";
    }
}

$b1 = new Book("1984", "George Orwell", 328);
$b2 = new Book("Short Stories", "N. Mulenga");   // uses default 100

echo $b1->summary() . "<br>";
echo $b2->summary();
1984 by George Orwell (328 pages) Short Stories by N. Mulenga (100 pages)
Quick quiz

When does __construct run?

Quick quiz

What does public string $name inside constructor brackets do (PHP 8+)?

๐Ÿ”‘ Key points
  • A constructor is a special method named __construct that runs automatically on new.
  • It's the registration desk: it can demand data, so no half-built objects exist.
  • $this->name = $name; โ€” left side is the object's property, right side is the incoming parameter.
  • PHP 8 promoted properties: public string $name in the constructor brackets declares + assigns in one go.
  • Constructors can compute values and enforce rules, not just store data.
  • __destruct runs automatically when the object dies โ€” used rarely, for cleanup.