Traits advanced

Resolve with insteadof

Two traits may bring a method with the same name. PHP stops and asks you to pick the winner.

The insteadof rule names the choice inside the use block. The losing copy stays out of the class.

trait A { public function hello(): void { echo "A"; } } trait B { public function hello(): void { echo "B"; } } class Greeter { use A, B { A::hello insteadof B; } }

Alias with as

The as keyword keeps both copies under fresh names. One method keeps the main name, and the other gains an alias.

Call each form where it fits. Both bodies stay live with no extra wrapper code.

class Greeter { use A, B { A::hello insteadof B; B::hello as helloFromB; } }

Compose several

Small traits combine into bigger behavior. Each trait covers one skill, and the class lists the parts it needs.

One use line can name several traits. The class reads like a short parts list with no deep tree involved.

trait Loggable { public function log(string $m): void { echo $m; } } trait Timed { public function now(): int { return time(); } } class Worker { use Loggable, Timed; }

Trait methods

Trait methods can carry default logic or stay abstract. The class fills in the abstract parts with its own data.

Shared checks live in the trait once, while each class plugs in its own measure. That split removes copied logic.

trait Measurable { abstract public function size(): int; public function empty(): bool { return $this->size() === 0; } }

Next: Interfaces advanced

Автор статьи: Arthur Isaev