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| 欢迎光临 一起源码网 (https://www.171739.xyz/) | Powered by Discuz! X3.3 |