The trait Keyword

The keyword trait is used to create traits - a mechanism for code reuse in PHP. Traits are similar to classes but are intended for grouping functionality into small and understandable units. They can be included in classes using the keyword use.

Syntax

phptrait TraitName {
  // trait properties and methods
  public function method1() {
    // implementation
  }
}

Example

Let's create a simple trait and connect it to a class:

php<?php
  trait Logger {
    public function log($message) {
      echo "Logging: " . $message;
    }
  }

  class User {
    use Logger;
  }

  $user = new User();
  $user->log("User created");
?>

Code execution result:

php'Logging: User created'

Example

A class can use several traits simultaneously:

php<?php
  trait Timestamp {
    public function getCurrentTime() {
      return date('Y-m-d H:i:s');
    }
  }

  trait Serializer {
    public function toJson($data) {
      return json_encode($data);
    }
  }

  class Product {
    use Timestamp, Serializer;
  }

  $product = new Product();
  echo $product->getCurrentTime();
?>

Code execution result:

php'2023-11-15 14:30:00'

See Also

  • the class command,
    which is used to declare classes
  • the interface command,
    which is used to declare interfaces