Review a generated wallet object

from Object-oriented programming
PHP 8.3.33 advanced 8 min 4 issues to find

Review this generated class before it holds account balances.

Model a wallet whose integer-cent balance never becomes negative, inject a narrow audit interface, and expose one validated withdrawal operation.

php
final class Wallet
{
    public int $balanceCents;

    public function __construct(int $balanceCents, $audit)
    {
        $this->balanceCents = $balanceCents;
        $this->audit = $audit;
    }

    public function withdraw(int $cents): bool
    {
        if ($cents > $this->balanceCents) {
            return false;
        }
        $this->balanceCents -= $cents;
        $this->audit->record("withdrew {$cents}");
        return true;
    }

    public function __call(string $name, array $arguments): mixed
    {
        return $this->audit->$name(...$arguments);
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error