Info
Open the page on your phone

What are traits and where are they used?

A trait in PHP is a mechanism that allows incorporating a set of methods into a class for use in other classes without the need for inheritance. Traits provide the ability to use multiple inheritance, enabling classes to contain functionality from various sources.

Example usage of a trait in PHP:

                        
trait Logger {
    public function log($message) {
        echo $message;
    }
}

class User {
    use Logger;

    public function register() {
        // User registration implementation
        $this->log('User registered successfully');
    }
}

$user = new User();
$user->register();

                        
                    

In this example, the User class uses the Logger trait, which contains the log method. The User class inherits the functionality of the trait and can use its method.