Trait single case
Examples are as follows
<?phptrait Singleton {/** * private construct, generally defined by us ing class *///private function construct () {} public static function getinstance () {static $_instan CE = NULL; $class = class; Return $_instance?: $_instance = new $class; Public Function Clone () {trigger_error (' cloning '). CLASS. ' is not allowed. ', e_user_error); The Public Function wakeup () {trigger_error (' unserializing '). CLASS. ' is not allowed. ', e_user_error); }}/*** Example usage*/class foo {use singleton; Private Function construct () {$this->name = ' foo '; }}class Bar {use singleton; Private Function construct () {$this->name = ' bar '; }} $foo = Foo::getinstance (), echo $foo->name; $bar = Bar::getinstance (); Echo $bar->name;
Calling the Trait method
Although not obvious, if the trait method can be defined as a static method in a normal class, it can be called
Examples are as follows
<?php trait Foo { function bar () { return ' Baz '; }} Echo Foo::bar (), "\\n";?>
Class and trait
Class returns the class name,trait of Use trait returns trait name
Examples such as the following
<?phptrait testtrait {public Function TestMethod () {echo "Class:". CLASS. Php_eol; echo "Trait:". TRAIT. Php_eol; }}class BaseClass {use testtrait;} Class TestClass extends BaseClass {} $t = new TestClass (); $t->testmethod ();//class:baseclass//trait:testtrait