Classes and Objects
A class defines properties and methods. new creates an object, $this refers to the current object and -> accesses members. Constructor promotion declares and sets properties right in the constructor. Visibility keywords are public, protected and private.
Example
class Student {
public function __construct(private string $name, private int $score = 0) {}
public function addPoints(int $p): static {
$this->score += $p;
return $this;
}
public function describe(): string {
return "{$this->name} has {$this->score}";
}
}
$s = new Student("Ada", 70);
echo $s->addPoints(5)->describe(), "\n";Result
Ada has 75
Exercise
Refer to the current object.
return ->name;
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.