关于Trait
2016-09-29 本文已影响0人
Wisspedia
-
trait
是为了给类似PHP的单继承语言而准备的一种代码复用机制。trait
不能被实例化。trait
用use + traitname
关键词调用。 - 从基类继承的成员会被
trait
插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了trait的方法,而trait
则覆盖了被继承的方法。 - 通过逗号分隔,在use声明列出多个
trait
,都可以插入到一个类中。 - 如果
trait
定义了一个属性,那类将不能定义同样名称的属性,否则会产生一个错误。如果该属性在类中的定义与在trait
中的定义兼容(同样的可见性和初始值)则错误的级别是E_STRICT
,否则是一个致命错误。 - 如果一个
trait
包含一个静态变量,每个使用这个trait
的类都包含 一个独立的静态变量。
Example using parent class:
<?php
class TestClass {
public static $_bar;
}
class Foo1 extends TestClass { }
class Foo2 extends TestClass { }
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
?>
Example using trait:
<?php
trait TestTrait {
public static $_bar;
}
class Foo1 {
use TestTrait;
}
class Foo2 {
use TestTrait;
}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: Hello World
?>```