Trait 的抽象成员
为了对使用的类施加强制要求,trait 支持抽象方法的使用。
表示通过抽象方法来进行强制要求的例子
<?phptrait 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 的静态成员
Traits 可以被静态成员静态方法定义。
静态变量的例子
<?phptrait Counter { public function inc() { static $c = 0; $c = $c + 1; echo "$c\n"; }}class C1 { use Counter;}class C2 { use Counter;}$o = new C1(); $o->inc(); // echo 1$p = new C2(); $p->inc(); // echo 1?>
静态方法的例子
<?phptrait StaticExample { public static function doSomething() { return 'Doing something'; }}class Example { use StaticExample;}Example::doSomething();?>
静态变量和静态方法的例子
<?phptrait Counter { public static $c = 0; public static function inc() { self::$c = self::$c + 1; echo self::$c . "\n"; }}class C1 { use Counter;}class C2 { use Counter;}C1::inc(); // echo 1C2::inc(); // echo 1?>
属性
Trait 同样可以定义属性。
定义属性的例子
<?phptrait PropertiesTrait { public $x = 1;}class PropertiesExample { use PropertiesTrait;}$example = new PropertiesExample;$example->x;?>
如果 trait 定义了一个属性,那类将不能定义同样名称的属性,否则会产生一个错误。如果该属性在类中的定义与在 trait 中的定义兼容(同样的可见性和初始值)则错误的级别是 E_STRICT,否则是一个致命错误。
冲突的例子
<?phptrait PropertiesTrait { public $same = true; public $different = false;}class PropertiesExample { use PropertiesTrait; public $same = true; // Strict Standards public $different = true; // 致命错误}?>
Use的不同
不同use的例子
<?phpnamespace Foo\Bar;use Foo\Test; <mark>(本文来)源gaodaimacom搞#^代%!码&网(</mark><pre>搞gaodaima代码
// means \Foo\Test – the initial \ is optional?><?phpnamespace 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。
以上就是php trait 的静态成员、抽象成员、属性代码详解的详细内容,更多请关注搞代码gaodaima其它相关文章!