Traits are a mechanism in PHP that allow us to reuse sets of methods across multiple classes, avoiding the limitations of single inheritance (since PHP only supports single inheritance, meaning a class can inherit from only one other class).

Think of a trait like a bundle of methods that we can plug into different classes.

Why use Traits?

To reuse code across multiple classes.

To keep our class hierarchies clean without forcing inheritance.

To separate concerns (e.g., logging, notifications, utilities).

Defining a Trait — Syntax:

trait TraitName {
    // properties (optional)
    // methods
}

Using a Trait in a Class — Syntax:

class ClassName {
use TraitName;
}

Example:

trait Logger {
    public function log($message) {
        echo $message . "\n";
    }
}

class User {
    use Logger;

    public function createUser($name) {
        $this->log("Creating user: $name");
    }
}

class Product {
    use Logger;

    public function addProduct($productName) {
        $this->log("Adding product: $productName");
    }
}

$user = new User();
$user->createUser("John");

$product = new Product();
$product->addProduct("Laptop");

Output: