php trait is a code reuse mechanism prepared for single inheritance languages like PHP. Trait reduces the restrictions of single inheritance languages and allows developers to freely use independent classes in different hierarchies. Reuse methods.
Trait
Since PHP 5.4.0, PHP has implemented a code reuse method method, called a trait.
Trait is a code reuse mechanism prepared for single inheritance languages like PHP. Traits are designed to reduce the limitations of single-inheritance languages and allow developers to freely reuse methods in independent classes within different hierarchies. The semantics of Trait and Class composition define a way to reduce complexity and avoid the typical problems associated with traditional multiple inheritance and Mixin classes.
Trait is similar to Class, but is only designed to combine functionality in a fine-grained and consistent way. Cannot be instantiated through the trait itself. It adds a combination of horizontal features to traditional inheritance; that is, there is no need for inheritance between several Classes in an application.
Example #1 Trait Example
<?php trait ezcReflectionReturnInfo { function getReturnType() { /*1*/ } function getReturnDescription() { /*2*/ } } class ezcReflectionMethod extends ReflectionMethod { use ezcReflectionReturnInfo; /* ... */ } class ezcReflectionFunction extends ReflectionFunction { use ezcReflectionReturnInfo; /* ... */ } ?>
Priority ¶
Members inherited from the base class will be overridden by members inserted by the trait. The order of precedence is that members from the current class override the trait's methods, and the trait overrides the inherited methods.
Example #2 Precedence Example
Members inherited from the base class are overridden by the MyHelloWorld method in the inserted SayWorld Trait. Its behavior is consistent with the methods defined in the MyHelloWorld class. The order of precedence is that methods in the current class override trait methods, which in turn override methods in the base class.
<?php class Base { public function sayHello() { echo 'Hello '; } } trait SayWorld { public function sayHello() { parent::sayHello(); echo 'World!'; } } class MyHelloWorld extends Base { use SayWorld; } $o = new MyHelloWorld(); $o->sayHello(); ?>
The above routine will output:
Hello World!
Example #3 Another example of priority order
<?php trait HelloWorld { public function sayHello() { echo 'Hello World!'; } } class TheWorldIsNotEnough { use HelloWorld; public function sayHello() { echo 'Hello Universe!'; } } $o = new TheWorldIsNotEnough(); $o->sayHello(); ?>
The above routine will output:
Hello Universe!
For more related knowledge, please visit PHP中文网!
The above is the detailed content of What does php trait mean?. For more information, please follow other related articles on the PHP Chinese website!