trait to use in php

1, php The trait is what?

Looks like both interfaces like a class, actually not, Trait can be seen as part of the implementation class, can be mixed with one or more existing PHP class, its role is twofold: show what the class can do; provide modular achieve. Trait is a code-multiplexing, provides a flexible mechanism for code reuse single inheritance restriction PHP.

2, PHP Version:
php5.4 been introduced trait, its purpose is to reduce the duplication of code, code reusability increased.

3, trait usage scenario:
Imagine a situation when there is a need for a method used in many of the class, how to deal with?
Usually a general approach would be to write a base class implementation of this method in the base class, and all classes inherit this base class.

This is a processing method, but not the best approach. Inheritance is usually the case: several classes have great similarity. For example, as a base class people, students, workers, and other inherited "man" to expand this base class.

Thus, trait effects came out, trait can be used in multiple classes.

4, trait How to use:
reference example PHP manual:

An example of a

<? php
trait ezcReflectionReturnInfo {
function GetReturnType () {/ * 1 * /}
function getReturnDescription () {/ * 2 * /}
}

class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}

ezcReflectionFunction the extends ReflectionFunction {class
use ezcReflectionReturnInfo;
/ * ... * /
}
?>

. 1, declare a trait;
2, using the introduced trait use the class.
It is not very simple (manual escape)? Note that trait priority.

5, trait priority

Covered (knock blackboard) from members of the base class will be inherited trait inserted members. Priorities from members of the current class covers methods trait, and the trait is inherited cover method.

Priority: own method> trait approach> inherited methods (is like that.)

See examples

<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}

class TheWorldIsNotEnough {
use HelloWorld;
public function sayHello() {
echo 'Hello Universe!';
}
}

new new TheWorldIsNotEnough O = $ ();
$ O-> sayHello (); // output Universe is the Hello!
>?

Another point to note is: the use of multiple trait.

<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}

trait World {
public function sayWorld() {
echo 'World';
}
}

class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}

new new MyHelloWorld O = $ ();
$ O-> sayHello ();
$ O-> sayWorld ();
$ O-> sayExclamationMark ();
>?

summary: Trait is a kind of code reuse technology, as PHP's single inheritance limit provides a flexible mechanism for code reuse.

Guess you like

Origin www.cnblogs.com/fuoryao/p/11607020.html