search
HomeBackend DevelopmentPHP TutorialA way to achieve code reuse in PHP Traits new features, traits new features_PHP tutorial

A way to achieve code reuse in PHP traits new features, traits new features

I came across traits while reading the yii2 source code, so I studied it and wrote a blog to record it.

Since PHP 5.4.0, PHP implements a method of code reuse called traits.

Traits is a code reuse mechanism for single-inheritance languages ​​like PHP. Traits are designed to reduce the constraints of single-inheritance languages ​​and allow developers to freely reuse method sets in independent classes within different hierarchies. The semantics of traits and class composition define a way to reduce complexity and avoid the typical problems associated with traditional multiple inheritance and mixins.

Trait is similar to a class, but is only designed to combine functionality in a fine-grained and consistent way. Trait cannot be instantiated by itself. It adds a combination of horizontal features to traditional inheritance; that is, members of application classes do not need to be inherited.

Trait example

Copy code The code is as follows:

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 are 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 of priority

Copy code The code is as follows:

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!

Members inherited from the base class are overridden by the sayHello 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.

Another example of priority order

Copy code The code is as follows:

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!

Multiple traits

Separated by commas, list multiple traits in the use statement, which can all be inserted into a class.

Examples of usage of multiple traits

Copy code The code is as follows:

trait Hello {
Public function sayHello() {
echo 'Hello ';
}
}
trait World {
Public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld {
Use Hello, World;
Public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

The above routine will output: Hello World!

Conflict resolution

If two traits insert a method with the same name, a fatal error will occur if the conflict is not explicitly resolved.

In order to resolve the naming conflict of multiple traits in the same class, you need to use the insteadof operator to explicitly specify which of the conflicting methods to use.

The above method only allows to exclude other methods. The as operator can introduce one of the conflicting methods under another name.

Examples of conflict resolution

Copy code The code is as follows:

trait A {
Public function smallTalk() {
echo 'a';
}
Public function bigTalk() {
echo 'A';
}
}
trait B {
Public function smallTalk() {
echo 'b';
}
Public function bigTalk() {
echo 'B';
}
}
class Talker {
Use A, B {
          B::smallTalk instead of A;
A::bigTalk instead of B;
}
}
class Aliased_Talker {
Use A, B {
          B::smallTalk instead of A;
A::bigTalk instead of B;
          B::bigTalk as talk;
}
}
?>

In this example Talker uses traits A and B. Since A and B have conflicting methods, they define using smallTalk from trait B and bigTalk from trait A.

Aliased_Talker uses the as operator to define talk as an alias of B's ​​bigTalk.

Modify method access control

Using as syntax can also be used to adjust the access control of methods.

Example of modifying method access control

Copy code The code is as follows:

trait HelloWorld {
Public function sayHello() {
echo 'Hello World!';
}
}
// Modify the access control of sayHello
class MyClass1 {
Use HelloWorld { sayHello as protected; }
}
//Give the method an alias that changes access control
// The access control of the original sayHello has not changed
class MyClass2 {
Use HelloWorld { sayHello as private myPrivateHello; }
}
?>

Compose trait from trait

Just as classes can use traits, other traits can also use traits. By using one or more traits when a trait is defined, it can combine some or all members of other traits.

Examples of composing traits from traits

Copy code The code is as follows:

trait Hello {
Public function sayHello() {
echo 'Hello ';
}
}
trait World {
Public function sayWorld() {
echo 'World!';
}
}
trait HelloWorld {
Use Hello, World;
}
class MyHelloWorld {
Use HelloWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>

The above routine will output: Hello World!

Abstract member of Trait

In order to enforce requirements on the classes used, traits support the use of abstract methods.

Indicates an example of enforcing requirements through abstract methods

Copy code The code is as follows:

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;
}
}
?>

Static member of Trait

Traits can be defined by static members and static methods.

Example of static variable

Copy code The code is as follows:

trait Counter {
Public function inc() {
         static $c = 0;
          $c = $c + 1;
           echo "$cn";
}
}
class C1 {
Use Counter;
}
class C2 {
Use Counter;
}
$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

Example of static method

Copy code The code is as follows:

trait StaticExample {
Public static function doSomething() {
          return 'Doing something';
}
}
class Example {
Use StaticExample;
}
Example::doSomething();
?>

Examples of static variables and static methods

Copy code The code is as follows:

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
?>

Properties
Traits can also define properties.

Example of defining attributes

Copy code The code is as follows:

trait PropertiesTrait {
Public $x = 1;
}
class PropertiesExample {
Use PropertiesTrait;
}
$example = new PropertiesExample;
$example->x;
?>

If the trait defines a property, the class cannot define a property 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) then the error level is E_STRICT, otherwise it is a fatal error.

Examples of conflicts

Copy code The code is as follows:

trait PropertiesTrait {
Public $same = true;
Public $different = false;
}
class PropertiesExample {
Use PropertiesTrait;
Public $same = true; // Strict Standards
Public $different = true; // Fatal error
}
?>

Differences in Use

Examples of different uses

Copy code The code is as follows:

namespace FooBar;
use FooTest; // means FooTest - the initial is optional
?>
namespace FooBar;
class SomeClass {
Use FooTest; // means FooBarFooTest
}
?>

The first use is use FooTest for namespace, and FooTest is found. The second use is to use a trait, and FooBarFooTest is found.

__CLASS__ and __TRAIT__
__CLASS__ returns the class name of the use trait, __TRAIT__ returns the trait name

An example is as follows

Copy code The code is as follows:

trait TestTrait {
Public function testMethod() {
echo "Class: " . __CLASS__ . PHP_EOL;
echo "Trait: " . __TRAIT__ . PHP_EOL;
}
}
class BaseClass {
Use TestTrait;
}
class TestClass extends BaseClass {
}
$t = new TestClass();
$t->testMethod();
//Class: BaseClass
//Trait: TestTrait

Trait singleton

Examples are as follows

Copy code The code is as follows:

trait singleton {
/**
     * private construct, generally defined by using class
    */
//private function __construct() {}
Public static function getInstance() {
         static $_instance = NULL;
          $class = __CLASS__;
          return $_instance ?: $_instance = new $class;
}
Public function __clone() {
         trigger_error('Cloning '.__CLASS__.' is not allowed.',E_USER_ERROR);
}
Public function __wakeup() {
         trigger_error('Unserializing '.__CLASS__.' is not allowed.',E_USER_ERROR);
}
}
/**
* Example Usage
*/
class foo {
Use singleton;
Private function __construct() {
$this->name = 'foo';
}
}
class bar {
Use singleton;
Private function __construct() {
            $this->name = 'bar';
}
}
$foo = foo::getInstance();
echo $foo->name;
$bar = bar::getInstance();
echo $bar->name;

Call trait method

Although it is not obvious, if the Trait method can be defined as a static method in a normal class, it can be called

Examples are as follows

Copy code The code is as follows:

trait Foo {
Function bar() {
         return 'baz';
}
}
echo Foo::bar(),"\n";
?>

Are you familiar with the new features of traits? I hope this article can be helpful to you.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/959108.htmlTechArticlePHP A method to achieve code reuse traits new features, traits new features came into contact with traits when reading the yii2 source code , I just studied it and wrote a blog to record it. Since PHP 5.4...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool