Open In App

How to define the Trait in PHP?

A trait in PHP is a mechanism for code reuse that enables the composition of methods into classes independent of inheritance. Traits encapsulate reusable pieces of code and allow them to be shared across multiple classes.

Defining a Trait:

trait Loggable {
public function log($message) {
echo "Logging: $message";
}
}

Using Traits:

class MyClass {
use Loggable;

public function process() {
$this->log("Processing...");
}
}

Multiple Traits:

PHP allows a class to use multiple traits by separating them with commas in the use statement.

Conflict Resolution:

Article Tags :