Analysis of Trait in PHP

不言
Release: 2023-04-02 19:30:01
Original
1341 people have browsed it

This article mainly introduces the analysis of Traits in PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Since PHP 5.4.0, PHP has implemented A method of code reuse called traits.

Trait literally means "characteristics" and "characteristics". We can understand that using the Trait keyword can add new characteristics to classes in PHP.

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.

Usage: By using the use keyword in the class, declare the Trait name to be combined. The specific Trait declaration uses the Trait keyword. Trait cannot be instantiated.

1. Basics of Traits

<?php
header("Content-type:text/html;charset=utf-8");
trait Test{public function hello1(){        
return "Test::hello1()";
    }
}class demo1{    
use Test;
}$obj = new demo1();echo $obj->hello1().&#39;<br />&#39;;//Test::hello1()
Copy after login

2. Priority

<?php
class Base {    
public function sayHello() {        
echo &#39;Hello &#39;;
    }
}

trait SayWorld {    
public function sayHello() {
        parent::sayHello();        
        echo &#39;World!&#39;;
    }
}class MyHelloWorld extends Base {    
use SayWorld;
}$o = new MyHelloWorld();$o->sayHello();//Hello World!
Copy after login

<?php

trait HelloWorld {    
public function sayHello() {        
echo &#39;Hello World!&#39;;
    }
}class TheWorldIsNotEnough {    
use HelloWorld;    
public function sayHello() {        
echo &#39;Hello Universe!&#39;;
    }
}
$o = new TheWorldIsNotEnough();
$o->sayHello();//Hello Universe!
Copy after login

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.

3. Multiple Traits

Separate by commas and list multiple traits in the use statement, they can all be inserted into a class.

<?php

trait Hello {    
public function sayHello() {        
echo &#39;Hello &#39;.&#39;<br />&#39;;
    }
}

trait World {    
public function sayWorld() {        
echo &#39;World&#39;.&#39;<br />&#39;;
    }
}class MyHelloWorld {    
use Hello, World;    
public function sayExclamationMark() {        
echo &#39;!&#39;.&#39;<br />&#39;;
    }
}$o = new MyHelloWorld();$o->sayHello();//Hello$o->sayWorld();//World$o->sayExclamationMark();//!
Copy after login

4. Conflict resolution

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

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.

<?php

trait A{    public function smallTalk(){        echo &#39;a&#39;;
    }    public function bigTalk(){        echo &#39;A&#39;;
    }
}

trait B{    public function smallTalk(){        echo &#39;b&#39;;
    }    public function bigTalk(){        echo &#39;B&#39;;
    }
}class Talker{    use A,B{
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}$obj = new Talker();$obj->smallTalk();//b$obj->bigTalk();//A
Copy after login

The above method only allows to exclude other methods. The as operator can introduce an alias for a method. Note that the as operator does not rename the method, nor does it affect its methods.

<?php

trait A{    public function smallTalk(){        echo &#39;a&#39;;
    }    public function bigTalk(){        echo &#39;A&#39;;
    }
}

trait B{    public function smallTalk(){        echo &#39;b&#39;;
    }    public function bigTalk(){        echo &#39;B&#39;;
    }
}class Talker{    use A,B{
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as b_bigTalk;
        A::smallTalk as a_smallTalk;
    }
}$obj = new Talker();$obj->smallTalk();//b$obj->bigTalk();//A$obj->b_bigTalk();//B$obj->a_smallTalk();//a
Copy after login

5. Modify the access control of the method

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

<?php

trait A{    private function smallTalk(){        echo &#39;a&#39;;
    }
}class Talker{    use A{
        smallTalk as public aaa;
    }
}$obj = new Talker();$obj->aaa();//a
Copy after login

6. Traits group

Just as class can use traits, other traits can also use traits. By using one or more traits when defining a trait, you can combine some or all members of other traits.

<?php

trait Hello{    public function sayHello(){        echo &#39;Hello &#39;;
    }
}

trait World{    public function sayWorld(){        echo &#39;World !&#39;;
    }
}

trait HelloWorld{    use Hello,World;
}class Talker{    use HelloWorld;
}$obj = new Talker();$obj->sayHello();//Hello$obj->sayWorld();//World !
Copy after login

7. Abstract members

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

<?php

trait Hello{    public function sayWorld(){        echo &#39;Hello &#39;.$this->getWorld();
    }    abstract public function getWorld();
}class Talker{    private $world;    use Hello;    public function getWorld(){        return $this->world;
    }    public function setWorld($val){        $this->world = $val;
    }
}$obj = new Talker();$obj->setWorld("Trait !");$obj->sayWorld();//Hello Trait !
Copy after login

8. Traits static members

Traits can be defined by static member static methods.

<?php

trait HelloWorld{    public static function sayHelloWorld(){        echo &#39;Hello World !&#39;;
    }
}class Talker{    use HelloWorld;
}
Talker::sayHelloWorld();//Hello World !
Copy after login

<?php

trait Counter{    public function inc(){        static $c = 0;        $c++;        echo "$c\n";
    }
}class C1{    use Counter;
}class C2{    use Counter;
}$c1 = new C1();$c1->inc();//1$c1_1 = new C1();$c1_1->inc();//2$c2 = new C2();$c2->inc();//1
Copy after login

9. Attributes

Trait can also define attributes.

<?php

trait PropertiesTrait {    public $x = 1;
}class PropertiesExample {    use PropertiesTrait;
}$example = new PropertiesExample;echo $example->x;//1
Copy after login

Trait After defining an attribute, the class cannot define attributes with the same name, otherwise a fatal error will occur. There is one exception: properties are compatible (same access visibility, initial default value). Before PHP 7.0, if the attribute was compatible, there would be an E_STRICT reminder.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use Elasticsearch in PHP

Instructions for PHP timer

The above is the detailed content of Analysis of Trait in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!