"how to write trait in yii2?" Code Answer


in general:

a trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. it is not possible to instantiate a trait on its own.

trait hello {
    public function sayhello() {
        echo 'hello ';

trait world {
    public function sayworld() {
        echo 'world';

class myhelloworld {
    use hello, world;
    public function sayexclamationmark() {
        echo '!';

$o = new myhelloworld();

use behavior then traits mainly for yii.

check this out:

reasons to use behaviors:

behavior classes, like normal classes, support inheritance. traits, on the other hand, can be considered as language-supported copy and paste. they do not support inheritance.

By Fady on April 30 2022
Only authorized users can answer the Search term. Please sign in first, or register a free account.