Trait 的抽象成員
為了對(duì)使用的類施加強(qiáng)制要求,trait 支持抽象方法的使用。
表示通過(guò)抽象方法來(lái)進(jìn)行強(qiáng)制要求的例子
<?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 的靜態(tài)成員
Traits 可以被靜態(tài)成員靜態(tài)方法定義。
靜態(tài)變量的例子
<?php trait 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 ?>
靜態(tài)方法的例子
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
<?php trait StaticExample { public static function doSomething() { return 'Doing something'; } } class Example { use StaticExample; } Example::doSomething(); ?>
靜態(tài)變量和靜態(tài)方法的例子
<?php trait 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 1 C2::inc(); // echo 1 ?>
Trait 同樣可以定義屬性。
定義屬性的例子
<?php trait PropertiesTrait { public $x = 1; } class PropertiesExample { use PropertiesTrait; } $example = new PropertiesExample; $example->x; ?>
如果 trait 定義了一個(gè)屬性,那類將不能定義同樣名稱的屬性,否則會(huì)產(chǎn)生一個(gè)錯(cuò)誤。如果該屬性在類中的定義與在 trait 中的定義兼容(同樣的可見(jiàn)性和初始值)則錯(cuò)誤的級(jí)別是?E_STRICT,否則是一個(gè)致命錯(cuò)誤。
沖突的例子
<?php trait PropertiesTrait { public $same = true; public $different = false; } class PropertiesExample { use PropertiesTrait; public $same = true; // Strict Standards public $different = true; // 致命錯(cuò)誤 } ?>
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 } ?>
第一個(gè)use是用于 namespace 的 use Foo\Test,找到的是?\Foo\Test,第二個(gè) use 是使用一個(gè)trait,找到的是\Foo\Bar\Foo\Test。
以上就是php trait 的靜態(tài)成員、抽象成員、屬性代碼詳解的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個(gè)人都需要一臺(tái)速度更快、更穩(wěn)定的 PC。隨著時(shí)間的推移,垃圾文件、舊注冊(cè)表數(shù)據(jù)和不必要的后臺(tái)進(jìn)程會(huì)占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://m.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)