WeCodeAcademy

PHP Traits, Namespaces and Enums

ExamplePHP
<?php
namespace App\Models;

trait Greets {
  public function hello(): string {
    return "Hello from " . static::class;
  }
}

enum Status: string {
  case Active = "active";
  case Banned = "banned";

  public function label(): string {
    return ucfirst($this->value);
  }
}

final class User {
  use Greets;
  public function __construct(public readonly string $name, public Status $status = Status::Active) {}
}

$u = new User("Ada");
echo $u->hello(), "\n";
echo $u->status->label(), "\n";
echo Status::from("banned")->name, "\n";
echo json_encode(array_map(fn($c) => $c->value, Status::cases())), "\n";
Output
Hello from App\Models\User
Active
Banned
["active","banned"]

A trait shares methods between classes. Namespaces organise names, readonly properties cannot change after creation, and enums model a fixed set of values.

Quick check

What does a readonly property allow?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.