0
0
PHPprogramming~5 mins

Trait declaration and usage in PHP

Choose your learning style9 modes available
Introduction

Traits let you share code between classes easily without repeating yourself.

When you want to add the same method to many classes without inheritance.
When different classes need similar behavior but don't share a parent class.
When you want to organize reusable code in small pieces.
When you want to avoid duplicating code in multiple places.
Syntax
PHP
<?php
trait TraitName {
    public function methodName() {
        // code here
    }
}

class ClassName {
    use TraitName;
}

Traits are declared with the trait keyword.

Use the use keyword inside a class to include a trait.

Examples
This example shows a trait Logger with a method log. The class User uses it to print a message.
PHP
<?php
trait Logger {
    public function log($msg) {
        echo "Log: $msg\n";
    }
}

class User {
    use Logger;
}

$user = new User();
$user->log('User created');
This example shows a class using two traits to get two methods.
PHP
<?php
trait Hello {
    public function sayHello() {
        echo "Hello!\n";
    }
}

trait Bye {
    public function sayBye() {
        echo "Goodbye!\n";
    }
}

class Greeter {
    use Hello, Bye;
}

$g = new Greeter();
$g->sayHello();
$g->sayBye();
Sample Program

This program defines a trait Sharable with a method share. Two classes Post and Photo use this trait to share content. Both objects can call share() without repeating code.

PHP
<?php
trait Sharable {
    public function share() {
        echo "Sharing content...\n";
    }
}

class Post {
    use Sharable;
}

class Photo {
    use Sharable;
}

$post = new Post();
$photo = new Photo();

$post->share();
$photo->share();
OutputSuccess
Important Notes

If two traits have methods with the same name, you can resolve conflicts using insteadof and as keywords.

Traits cannot be instantiated on their own; they must be used inside classes.

Summary

Traits help reuse code in multiple classes without inheritance.

Declare traits with trait and include them in classes with use.

Traits make your code cleaner and avoid duplication.