Classes and objects
<?php
class Dog
{
private array $tricks = [];
public function __construct(public string $name) {}
public function learn(string $trick): void
{
$this->tricks[] = $trick;
}
public function describe(): string
{
return "{$this->name} knows " . count($this->tricks) . " tricks";
}
}
$rex = new Dog("Rex");
$rex->learn("sit");
echo $rex->describe(); // Rex knows 1 tricks
new Dog("Rex")creates an object and runs__construct.$thisis the current object;->reaches its properties and methods.- Constructor promotion (PHP 8): writing
public string $namein the constructor's parameters declares the property and sets it in one go.
Visibility
| Keyword | Accessible from |
|---|---|
public |
anywhere |
protected |
the class and its children |
private |
only inside the class |
Keep data private and change it through methods, so the class can keep it valid.
readonly
A readonly property (PHP 8.1) can be set once, in the constructor, and never changed: trying throws an Error.
Inside a double-quoted string, use {$this->name} to insert a property.
Your task
Write class Product:
- constructor with promoted
public readonly string $nameandpublic readonly float $price, - a private stock starting at 0,
restock(int $quantity),stock(): int,sell(int $quantity): float: throws anExceptionif there is not enough stock; otherwise reduces stock and returns price times quantity.