"how to write trait in yii2?" Code Answer

5

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.

<?php
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();
$o->sayhello();
$o->sayworld();
$o->sayexclamationmark();
?>

use behavior then traits mainly for yii.

check this out:
http://www.yiiframework.com/doc-2.0/guide-concept-behaviors.html#comparison-with-traits

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.