Home > Article > Backend Development > Detailed explanation of trait singleton and calling instances in PHP
Trait单例
实例如下
<?php trait singleton { /** * private construct, generally defined by using class */ //private function construct() {} public static function getInstance() { static $_instance = NULL; $class = CLASS; return $_instance ?: $_instance = new $class; } public function clone() { trigger_error('Cloning '.CLASS.' is not allowed.',E_USER_ERROR); } 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;
调用trait方法
虽然不很明显,但是如果Trait的方法可以被定义为在普通类的静态方法,就可以被调用
实例如下
<?php trait Foo { function bar() { return 'baz'; } } echo Foo::bar(),"\\n"; ?>
CLASS和TRAIT
CLASS 返回 use trait 的 class name,TRAIT返回 trait name
示例如下
<?php trait 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
The above is the detailed content of Detailed explanation of trait singleton and calling instances in PHP. For more information, please follow other related articles on the PHP Chinese website!