Home Backend Development PHP Tutorial What is Trait? Sharing the declaration and usage tips of Trait in php

What is Trait? Sharing the declaration and usage tips of Trait in php

May 17, 2017 pm 02:14 PM

What is Trait?

php has supported Trait features since version 5.4. It is very similar to the Class class, and all common Trait features in the class can be implemented. Traits are not used to replace classes, but to "mix" into classes. Traits are designed to reduce the limitations of single-inheritance languages ​​and allow developers to freely reuse method sets 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. For example, two abstract classes need to be inherited at the same time, which is a function that the PHP language does not support. Trait is to solve this problem. Or it can be understood that the inheritance class chain isolates the subclass from inheriting certain characteristics of the parent class, which is equivalent to calling the members of the Trait first if there is a Trait when using the characteristics of the parent class.

Declaration of Trait

You need to use the class keyword to declare a class. Of course, you must also use the trait keyword to declare a Trait. The characteristics of a class Traits are generally available. Trait supports modifiers such as final, static and abstract , so Trait also supports the use of abstract methods, class definition static methods, and of course attributes can also be defined. But Trait cannot be instantiated using new like a class, because Trait is used when mixed into a class and cannot be used alone. If we compare Interface and Trait, Trait will be more convenient.

The simple Trait declaration code is as follows:

<?php
//使用 trait 关键字申明一个 Trait,需要php5.4以上的版本
trait dome{
 public $a = true;        //声明成员属性
 static $b = 1;           //使用 static 关键字声明静态变量
 function method1(){
 }      //声明成员方法
 abstract public function method2(); //加入抽象修饰符,说明调用类必须实现它
}
?>
Copy after login


Basic use of Trait

Different from classes, Trait cannot instantiate objects by itself and must be mixed into a class for use. It is equivalent to copying the members in the Trait to the class, and using the class just like using its own members. If you want to use Trait in a class. Traits need to be mixed into the class through the use keyword.

The code is as follows:

<?php
//使用 trait 关键字申明一个 Trait,有两个成员方法
trait dome{
 function method1(){
 }      //声明成员方法
 function method2(){
 }      //声明成员方法
}
class dome1{    //申明一个类,类中混入 Trait
 use dome;    //使用 use 关键字在类中使用 dome
}
$obj = new dome1();   //实例化 dome1 对象
$obj->method1();      // 通过 dome1 对象,直接调用混入类 dome1 的成员方法 method1
$obj->method2();      // 通过 dome1 对象,直接调用混入类 dome1 的成员方法 method2
?>
Copy after login

In the above example, the use keyword is used to mix the members in dome into the dome1 class. You can also use the use keyword to mix multiple Traits at once and use them together. By separating with commas, multiple Traits can be listed in the use statement, and they can all be inserted into a class. It should be noted that conflicts will inevitably occur when multiple Traits are used at the same time. php5.4 brings related keyword syntax insteadof from the syntax aspect.

The sample code is as follows:

<?php
//使用 trait 关键字申明一个 Trait,有两个成员方法
trait dome1
{
 function fun()
 {
     echo "第一个 Trait 中的 fun 方法";
 }
}
trait dome2   //这里名称相同就会有冲突
{
 function fun()
 {
    echo "第二个 Trait 中的 fun 方法";
 }
}
class dome{
 use dome1,dome2{     // dome2 中申明
   dome1::fun insteadof dome2;  // 申明使用 dome1 中的 fun 替换
 }
}
$obj = new dome();
$obj->fun();       //  输出第一个 Trait 中的 fun 方法
?>
Copy after login

Not only can you use the use keyword in a class to mix members of Trait into the class, you can also use use in Trait Keyword mixes in members from another Trait. This forms a nesting between Traits. In order to enforce requirements on the classes used, Traits support the use of abstract methods. If you declare an abstract method that needs to be implemented in a Trait, the class that uses it must implement it first, just like inheriting an abstract class and must implement the abstract method in the class.

For more detailed usage, please refer to the official manual. But when you first start learning Trait, you should understand the following key points: 1. Trait will override the parent class method of the calling class.

2. Members inherited from the base class are overridden by members inserted by Trait. The order of precedence is: members from the current class override Trait methods, and Traits override inherited methods.

3. Trait cannot use new to instantiate objects like a class.

4. A single Trait can be composed of multiple Traits.

5. In a single class, use use to introduce Trait. You can introduce multiple Traits.

6. Trait supports modifiers, such as final, static, and abstract.

7. You can use insteadof and as operators to resolve conflicts between Traits.

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


【Related tutorial recommendations】

1. "

php.cn Dugu Jiujian (4)-php video Tutorial

2. Video tutorial: Declaration and usage skills of

trait characteristics: Collection of class methods to achieve code reuse

##3.
php practical video tutorial

The above is the detailed content of What is Trait? Sharing the declaration and usage tips 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles