php · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Somebody typed the seats in words. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Ticket {
public function __construct(public string $film, public int $seats) {}
}
$ticket = new Ticket("Paddington", "two");
echo "$ticket->seats seats for $ticket->film\n";
your turn
Your turn. Put a book on the shelf.
Fill in a title, an author and a number of pages, then run it. All three arrive through the constructor in one line.
fix it
Ava's name went missing. Can you find it?
- The error says
Undefined property: Player::$name. Compare the two parameters on line 3. What does one have that the other lacks? - Without
publicin front,$nameis an ordinary parameter. It disappears when the constructor finishes and never becomes a property. - Write
publicbeforestring $nameon line 3, then run it.
nailed it
your objects arrive ready to use. :D
__constructruns by itself whenevernewbuilds an object.- Write
publicbefore a parameter to promote it to a property. - Typed properties turn wrong values away with a
TypeError.
new words in your collection
- constructor
- constructor property promotion
- typed property
This lesson isn’t saved. A free account remembers every lesson you finish.