Home Backend Development PHP Tutorial Usage and examples of Trait in PHP

Usage and examples of Trait in PHP

Jan 29, 2020 pm 10:21 PM
trait

Usage and examples of Trait in PHP

PHP is a single-inheritance language. Before the emergence of PHP 5.4 Traits, PHP classes could not inherit properties or methods from two base classes at the same time. In order to solve this problem, PHP introduced Traits. This feature. (The combination function of Traits and Go language is somewhat similar)

Usage: Use the use keyword in the class to declare the Trait name to be combined, and the declaration of a specific Trait uses the trait keyword, and the Trait cannot be directly instantiated. change.

<?php
trait Drive {
    public $carName = &#39;BMW&#39;;
    public function driving() {
        echo "driving {$this->carName}\n";
    }
}
 
class Person {
    public function age() {
        echo "i am 18 years old\n";
    }
}
 
class Student extends Person {
    use Drive;
    public function study() {
        echo "Learn to drive \n";
    }
}
 
$student = new Student();
$student->study();  //输出:Learn to drive 
$student->age();    //输出:i am 18 years old
$student->driving();//输出:driving BMW
Copy after login

Conclusion:

The Student class inherits Person and has the age method.

By combining Drive, it has the driving method and attribute carName.

If there is a property or method with the same name in Trait, base class and this class, which one will be retained in the end? Test it with the following code:

<?php
 
trait Drive {
    public function hello() {
        echo "hello 周伯通\n";
    }
    public function driving() {
        echo "周伯通不会开车\n";
    }
}
 
class Person {
    public function hello() {
        echo "hello 大家好\n";
    }
    public function driving() {
        echo "大家都会开车\n";
    }
}
 
class Student extends Person {
    use Drive;//trait 的方法覆盖了基类Person中的方法,所以Person中的hello 和driving被覆盖
    public function hello() {
        echo "hello 新学员\n";//当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,所以此处hello会覆盖trait中的
        hello
    }
}
 
$student = new Student();
$student->hello();    //输出:hello 新学员
$student->driving();  //输出:周伯通不会开车
Copy after login

Conclusion: When a method or attribute has the same name, the method in the current class will override the trait's method, and the trait's method will override the method in the base class.

If you want to combine multiple Traits, separate the Trait names by commas:

use Trait1, Trait2;

What will happen if multiple Traits contain methods or properties with the same name? Woolen cloth? The answer is that when multiple combined Traits contain properties or methods with the same name, they need to be explicitly declared to resolve conflicts, otherwise a fatal error will occur.

<?php
trait Trait1 {
    public function hello() {
        echo "Trait1::hello\n";
    }
    public function hi() {
        echo "Trait1::hi\n";
    }
}
 
trait Trait2 {
    public function hello() {
        echo "Trait2::hello\n";
    }
    public function hi() {
        echo "Trait2::hi\n";
    }
}
 
class Class1 { 
    use Trait1, Trait2;
}
 
//输出:Fatal error:  Trait method hello has not been applied, because there are collisions with other trait
 methods on Class1 in
Copy after login

Use insteadof and as operators to resolve conflicts. Insteadof uses a method to replace another, while as gives an alias to the method. Please see the code for specific usage:

<?php
trait Trait1 {
    public function hello() {
        echo "Trait1::hello \n";
    }
    public function hi() {
        echo "Trait1::hi \n";
    }
}
trait Trait2 {
    public function hello() {
        echo "Trait2::hello\n";
    }
    public function hi() {
        echo "Trait2::hi\n";
    }
}
class Class1 {
    use Trait1, Trait2 {
        Trait2::hello insteadof Trait1;
        Trait1::hi insteadof Trait2;
    }
}
 
class Class2 {
    use Trait1, Trait2 {
        Trait2::hello insteadof Trait1;
        Trait1::hi insteadof Trait2;
        Trait2::hi as hei;
        Trait1::hello as hehe;
    }
}
 
$Obj1 = new Class1();
$Obj1->hello();
$Obj1->hi();
echo "\n";
$Obj2 = new Class2();
$Obj2->hello();
$Obj2->hi();
$Obj2->hei();
$Obj2->hehe();
Copy after login

Output

Trait2::hello
Trait1::hi 
 
Trait2::hello
Trait1::hi 
Trait2::hi
Trait1::hello
Copy after login
<?php
trait Hello {
    public function hello() {
        echo "hello,我是周伯通\n";
    }
}
class Class1 {
    use Hello {
        hello as protected;
    }
}
class Class2 {
    use Hello {
        Hello::hello as private hi;
    }
}
$Obj1 = new Class1();
$Obj1->hello(); # 报致命错误,因为hello方法被修改成受保护的
 
$Obj2 = new Class2();
$Obj2->hello(); # 输出: hello,我是周伯通,因为原来的hello方法仍然是公共的
$Obj2->hi();  # 报致命错误,因为别名hi方法被修改成私有的
Copy after login
Uncaught Error: Call to protected method Class1::hello() from context &#39;&#39; in D:\web\mytest\p.php:18
Copy after login

Trait can also be combined with Trait. Trait supports abstract methods, static properties and static methods. The test code is as follows:

<?php
trait Hello {
    public function sayHello() {
        echo "Hello 我是周伯通\n";
    }
}
 
trait World {
    use Hello;
    public function sayWorld() {
        echo "hello world\n";
    }
    abstract public function getWorld();
    public function inc() {
        static $c = 0;
        $c = $c + 1;
        echo "$c\n";
    }
    public static function doSomething() {
        echo "Doing something\n";
    }
}
 
class HelloWorld {
    use World;
    public function getWorld() {
        return &#39;do you get World ?&#39;;
    }
}
 
$Obj = new HelloWorld();
$Obj->sayHello();
$Obj->sayWorld();
echo $Obj->getWorld() . "\n";
HelloWorld::doSomething();
$Obj->inc();
$Obj->inc();
Copy after login

Output

Hello 我是周伯通
hello world
do you get World ?
Doing something12
Copy after login


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

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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP trait DTO: Simplifying the development of data transfer objects PHP trait DTO: Simplifying the development of data transfer objects Oct 12, 2023 am 09:04 AM

PHPtraitDTO: Simplifying the development of data transfer objects Introduction: In modern software development, data transfer objects (DataTransferObject, referred to as DTO) play an important role. DTO is a pure data container used to transfer data between layers. However, during the development process, developers need to write a large amount of similar code to define and operate DTOs. In order to simplify this process, the trait feature was introduced in PHP. We can use the trait feature to

In-depth understanding of the design patterns and practices of PHP trait DTO In-depth understanding of the design patterns and practices of PHP trait DTO Oct 12, 2023 am 08:48 AM

In-depth understanding of the design patterns and practices of PHPtraitDTO Introduction: In PHP development, design patterns are an essential part. Among them, DTO (DataTransferObject) is a commonly used design pattern used to encapsulate data transfer objects. In the process of implementing DTO, using traits can effectively improve the reusability and flexibility of the code. This article will delve into the design patterns and practices of traitDTO in PHP

PHP trait DTO: a key tool for optimizing the data transfer process PHP trait DTO: a key tool for optimizing the data transfer process Oct 12, 2023 pm 03:10 PM

PHPtraitDTO: A key tool for optimizing the data transmission process. Specific code examples are required. Introduction: During the development process, data transmission is a very common requirement, especially when data is transferred between different levels. In the process of transmitting this data, we often need to process, verify or convert the data to meet different business needs. In order to improve the readability and maintainability of the code, we can use PHPtraitDTO (DataTransferObject) to optimize

PHP trait DTO: achieving simplicity and flexibility in data transfer objects PHP trait DTO: achieving simplicity and flexibility in data transfer objects Oct 12, 2023 am 10:21 AM

PHPtraitDTO: Implementing simplicity and flexibility of data transfer objects Introduction: In the PHP development process, data transmission and processing are often involved. The DataTransferObject (DTO for short) is a design pattern that is used to transfer data between different layers. During the transmission process, DTO simplifies data operations by encapsulating data and providing public access methods. This article will introduce how to use PHPtrait to implement DT

PHP trait DTO: elegant data transfer object pattern PHP trait DTO: elegant data transfer object pattern Oct 12, 2023 am 08:34 AM

PHPtraitDTO: Elegant Data Transfer Object Pattern Overview: Data Transfer Object (DTO for short) is a design pattern used to transfer data between different layers. In applications, it is often necessary to obtain data from a database or external service and pass it between different layers of the application. The DTO mode can make data transmission more concise and clear, and also facilitates expansion and maintenance. In PHP, we can use traits to implement DTO

Implement a highly customizable data transfer framework using PHP trait DTO Implement a highly customizable data transfer framework using PHP trait DTO Oct 12, 2023 pm 12:46 PM

Implementing a highly customizable data transfer framework using PHPtraitDTO As websites and applications become more complex, data transfer becomes more and more important. In PHP, using DataTransferObject (DTO for short) to handle data transfer can greatly simplify the code and improve maintainability and scalability. This article will introduce how to use PHPtrait and DTO to implement a highly customizable data transfer framework and provide corresponding code examples.

PHP trait DTO: a key tool for optimizing the data transfer process PHP trait DTO: a key tool for optimizing the data transfer process Oct 12, 2023 am 09:27 AM

PHPtraitDTO: A key tool for optimizing the data transmission process. Specific code examples are required. In the development process, data transmission is a very critical link. How to transmit data efficiently has become one of the problems that developers need to solve. In PHP language, using traitDTO (DataTransferObject) can optimize the data transmission process and improve the efficiency of data transmission. This article will introduce what traitDTO is and how to use it to optimize the data transfer flow

How to extend custom PHP functions using traits? How to extend custom PHP functions using traits? Apr 23, 2024 am 09:27 AM

How to extend custom PHP functions using traits? Define a trait that contains extension methods. Use the use keyword to include traits into custom functions. Access trait methods through $this in custom functions.

See all articles