Trait 同樣可以定義屬性。
定義屬性的例子
代碼如下:
<?php
trait PropertiesTrait {
public $x = 1;
}
class PropertiesExample {
use PropertiesTrait;
}
$example = new PropertiesExample;
$example->x;
?>
如果 trait 定義了一個屬性,那類將不能定義同樣名稱的屬性,否則會產(chǎn)生一個錯誤。如果該屬性在類中的定義與在 trait 中的定義兼容(同樣的可見性和初始值)則錯誤的級別是 E_STRICT,否則是一個致命錯誤。
沖突的例子
代碼如下:
<?php
trait PropertiesTrait {
public $same = true;
public $different = false;
}
class PropertiesExample {
use PropertiesTrait;
public $same = true; // Strict Standards
public $different = true; // 致命錯誤
}
?>
Use的不同
不同use的例子
代碼如下:
<?php
namespace Foo\\\\Bar;
use Foo\\\\Test; // means \\\\Foo\\\\Test - the initial \\\\ is optional
?>
<?php
namespace Foo\\\\Bar;
class SomeClass {
use Foo\\\\Test; // means \\\\Foo\\\\Bar\\\\Foo\\\\Test
}
?>
第一個use是用于 namespace 的 use Foo\\\\Test,找到的是 \\\\Foo\\\\Test,第二個 use 是使用一個trait,找到的是\\\\Foo\\\\Bar\\\\Foo\\\\Test。
__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
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;
調(diào)用trait方法
雖然不很明顯,但是如果Trait的方法可以被定義為在普通類的靜態(tài)方法,就可以被調(diào)用
實例如下
代碼如下:
<?php
trait Foo {
function bar() {
return 'baz';
}
}
echo Foo::bar(),"\\\\\\\\n";
?>
相關學習推薦:PHP編程從入門到精通
更多關于云服務器,域名注冊,虛擬主機的問題,請訪問西部數(shù)碼官網(wǎng):m.ps-sw.cn