PHP Classes and Objects
ExamplePHP
<?php
class Person {
public function __construct(private string $name, private int $age) {}
public function birthday(): void {
$this->age++;
}
public function describe(): string {
return "{$this->name} is {$this->age}";
}
}
$p = new Person("Ada", 36);
$p->birthday();
echo $p->describe(), "\n";Output
Ada is 37
$this refers to the current object. Putting private in the constructor parameters (constructor promotion) declares and assigns the properties in one go.
Quick check
What does $this refer to?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.