Lesson 7 of 8 · 11 min

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.
  • $this is the current object; -> reaches its properties and methods.
  • Constructor promotion (PHP 8): writing public string $name in 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 $name and public readonly float $price,
  • a private stock starting at 0,
  • restock(int $quantity), stock(): int,
  • sell(int $quantity): float: throws an Exception if there is not enough stock; otherwise reduces stock and returns price times quantity.
index.php
<?php
class Product
{
}

$soap = new Product("Soap", 2.5);

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…