×

php · level 3 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A sets up each object the moment it is built.

Last time, each pet was built empty and filled in line by line. Forget a line and you have a pet with no name. A constructor fixes that. It is a method called __construct, and new runs it for you, passing along whatever is in the brackets.

Declaring each property, then a parameter, then copying one into the other gets tiring. With you write public in front of the parameter itself, and PHP creates the property and fills it in one go.

Each promoted property is a , so a wrong value is turned away at the door with a TypeError.

<?php
class Pet {
    public function __construct(
        public string $name,
        public int $age,
    ) {}

    public function describe(): string {
        return "$this->name is $this->age years old.";
    }
}
$bella = new Pet("Bella", 4);
echo $bella->describe() . "\n";

The two underscores at the start of __construct mark it as one of PHP's special methods.