Abstract members of Trait
In order to enforce requirements on the classes used, traits support the use of abstract methods.
Indicates an example of mandatory requirements through abstract methods
<?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's static members
Traits can be static members Static method definition.
staticExamples of variables
<?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 ?>
Examples of static methods
<?php trait StaticExample { public static function doSomething() { return 'Doing something'; } } class Example { use StaticExample; } Example::doSomething(); ?>
Examples of static variables and static methods
<?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 can also define attributes.
Example of defining attributes
<?php trait PropertiesTrait { public $x = 1; } class PropertiesExample { use PropertiesTrait; } $example = new PropertiesExample; $example->x; ?>
If a trait defines an attribute, the class will not be able to define an attribute with the same name, otherwise an error will be generated. If the property's definition in the class is compatible with its definition in the trait (same visibility and initial value) the error level is E_STRICT, otherwise it is a fatal error.
Conflict examples
<?php trait PropertiesTrait { public $same = true; public $different = false; } class PropertiesExample { use PropertiesTrait; public $same = true; // Strict Standards public $different = true; // 致命错误 } ?>
Differences in Use
Examples of different uses
<?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 } ?>
The first use is use Foo\Test for namespace, What was found was \Foo\Test. The second use was to use a trait and what was found was \Foo\Bar\Foo\Test.
The above is the detailed content of Detailed explanation of static members, abstract members, and attribute codes of php traits. For more information, please follow other related articles on the PHP Chinese website!