Traits advanced

A trait in PHP is a piece of behaviour copied into the classes that use it. The interesting part starts when two pieces carry the same method name, and the four blocks below show the rules that resolve it.

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.

<?php trait A { public function hello(): void { echo "A", PHP_EOL; } } trait B { public function hello(): void { echo "B", PHP_EOL; } } class Greeter { use A, B { A::hello insteadof B; } } $g = new Greeter(); $g->hello();

php conflict.php

A

Without the rule the file would not load: PHP would print Trait method B::hello has not been applied as Greeter::hello, because of collision with A::hello. With it, the chosen copy answers.

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.

<?php trait A { public function hello(): void { echo "A", PHP_EOL; } } trait B { public function hello(): void { echo "B", PHP_EOL; } } class Greeter { use A, B { A::hello insteadof B; B::hello as helloFromB; } } $g = new Greeter(); $g->hello(); $g->helloFromB();

php alias.php

A
B

The main name still belongs to the winning trait, and the alias reaches the body that lost the collision.

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.

<?php trait Loggable { public function log(string $m): void { echo $m, PHP_EOL; } } trait Timed { public function now(): int { return time(); } } class Worker { use Loggable, Timed; } $w = new Worker(); $w->log("hi"); echo gettype($w->now()), PHP_EOL; echo $w->now() > 0 ? "time ok" : "time bad", PHP_EOL;

php compose.php

hi
integer
time ok

One use line carried both skills, and gettype() on the time() stamp plus the positive check prove that the second trait really arrived.

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.

<?php trait Measurable { abstract public function size(): int; public function empty(): bool { return $this->size() === 0; } } class Box { use Measurable; public function __construct(private int $items) { } public function size(): int { return $this->items; } } echo (new Box(0))->empty() ? "empty" : "not empty", PHP_EOL; echo (new Box(3))->empty() ? "empty" : "not empty", PHP_EOL;

php methods.php

empty
not empty

The check exists once in the trait, and the box only supplies the count that the check asks for.

Exercises

  1. Remove the insteadof line and read the fatal error PHP prints.
  2. Alias a method to a second name and call both forms on one object.
  3. Compose three traits in one class, one of them with an abstract method.
  4. Give a trait a private property and a method that reads it, then use the trait in two classes.
  5. Explain why a trait is not a type and cannot be used in a parameter type.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What happens when two traits used by one class define the same method?

    Answer

    PHP refuses to load the class until a rule picks one

    A collision is a fatal error, and insteadof names the copy that the class keeps.

  2. What does insteadof do?

    Answer

    It keeps the named copy and drops the other one from the class

    The rule resolves the collision in favour of the trait named before the keyword.

  3. What does as add in a use block?

    Answer

    A second name for a trait method

    The alias gives the method another name that the class can call.

  4. Can a trait declare an abstract method?

    Answer

    Yes, and the using class has to implement it

    A trait may leave a method open and the class that uses it must provide the body.

  5. What does this program print? <?php 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; } } $g = new Greeter(); $g->hello();

    Answer

    A

    The insteadof rule kept the copy from trait A, so that body runs.

  6. What does this program print? <?php 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; B::hello as helloFromB; } } $g = new Greeter(); $g->hello(); $g->helloFromB();

    Answer

    AB

    The main name prints A and the alias reaches the body of B.

  7. What does this program print? <?php trait Loggable { public function log(string $m): void { echo $m; } } trait Timed { public function now(): int { return time(); } } class Worker { use Loggable, Timed; } $w = new Worker(); $w->log("hi"); echo gettype($w->now());

    Answer

    hiinteger

    The log call prints hi without a break and the type of the timestamp follows it.

  8. What does this program print? <?php trait Measurable { abstract public function size(): int; public function empty(): bool { return $this->size() === 0; } } class Box { use Measurable; public function size(): int { return 3; } } echo (new Box())->empty() ? "empty" : "not empty";

    Answer

    not empty

    The class filled in size() with 3, so the shared check answers false.

  9. Why is a trait not a type?

    Answer

    Because it is copied into the class and no object is an instance of it

    A trait is a piece of code, not a family of objects, so it cannot appear in a parameter type.

  10. What does gettype() return for the result of time()?

    Answer

    integer

    gettype() prints the long word integer for an int value.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev