typestar

Traits in PHP

Sharing behavior across classes without inheritance.

<?php
// a trait holds methods; use mixes them into any class
trait Greets {
    public function greet(): string {
        return "hi, I am " . $this->name();
    }
}

class Robot {
    use Greets;

    public function __construct(private int $id) {}

    public function name(): string {
        return "unit-" . $this->id;
    }
}

echo (new Robot(7))->greet(), "\n";

How it works

  1. A trait defines methods with no class of their own.
  2. use Greets; copies them into Robot as instance methods.
  3. The trait calls $this->name(), which the host class provides.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
329
Tokens
70
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 3 of 3 in Classes, step 18 of 27 in Language basics.

← Previous Next →

Traits in other languages