|
Trait 的抽象成员 为了对使用的类施加强制要求,trait 支持抽象方法的使用。 表示通过抽象方法来进行强制要求的例子 <?php
trait Hello {
public function sayHelloWorld() {
echo 'Hello'.$this->getWorld();
}
abstract public function getWorld();
}
class MyHelloWorld {
private $world;
use Hello;
public function getWorld() {
return $this->world;
}
public function setWorld($val) {
$this->world = $val;
}
}
?>Trait 的成员 可以被静态成员静态方法定义。 静态的例子 <?php
trait Counter {
public function inc() {
static $c = 0;
$c = $c + 1;
echo "$c
";
}
}
class C1 {
use Counter;
}
class C2 {
use Counter;
}
$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>静态方法的例子 <?php
trait StaticExample {
public static function doSomething() {
return 'Doing something';
}
}
class Example {
use StaticExample;
}
Example::doSomething();
?>静态变量和静态方法的例子 <?php
trait Counter {
public static $c = 0;
public static function inc() {
self::$c = self::$c + 1;
echo self::$c . "
";
}
}
class C1 {
use Counter;
}
class C2 {
use Counter;
}
C1::inc(); // echo 1
C2::inc(); // echo 1
?>Trait 同样可以定义属性。 定义属性的例子 <?php
trait PropertiesTrait {
public $x = 1;
}
class PropertiesExample {
use PropertiesTrait;
}
$example = new PropertiesExample;
$example->x;
?>如果 trait 定义了一个属性,那类将不能定义同样名称的属性,否则会产生一个错误。如果该属性在类中的定义与在 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 FooBar;
use FooTest; // means FooTest - the initial is optional
?>
<?php
namespace FooBar;
class SomeClass {
use FooTest; // means FooBarFooTest
}
?>第一个use是用于 namespace 的 use FooTest,找到的是 FooTest,第二个 use 是使用一个trait,找到的是FooBarFooTest。 |