search
HomeBackend DevelopmentPHP Tutorial[php classes and objects] trait

[php classes and objects] trait

Apr 17, 2018 pm 03:01 PM
phptrait


The content of this article is about [php classes and objects] traits, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it

Trait (PHP 5.4.0)

Translation Trait

  • Trait is a code reuse mechanism prepared for single inheritance languages ​​like PHP.

  • Trait is designed to reduce the limitations of single inheritance languages ​​and allow developers to freely reuse methods in independent classes within different hierarchies.

  • Trait is similar to Class, but is only designed to combine functionality in a fine-grained and consistent way.

  • Trait adds a combination of horizontal features to traditional inheritance; that is, there is no need for inheritance between several Classes in an application.


Priority

Members inherited from the base class will be 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.
(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.)

#Example #2 优先顺序示例<?phpclass Bases {
    public function sayHello() {
        echo &#39;Hello &#39;;
    }
}trait SayWorld {    public function sayHello() {
        parent::sayHello();        echo &#39;World!&#39;;
    }
}class MyHelloWorld extends Bases {
    // public function sayHello(){
    //     echo &#39;the class&#39;;
    // }
    use SayWorld;
}$o = new MyHelloWorld();$o->sayHello();    //output:   Hello World!?>
Example #3 另一个优先级顺序的例子<?phptrait 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();    //output:   Hello Universe!?>

More Traits

are separated by commas. Multiple traits are listed in the use statement, and they can all be inserted into a class.

Example #4 多个 trait 的用法<?phptrait Hello {    public function sayHello() {
        echo &#39;Hello &#39;;
    }
}trait World {    public function sayWorld() {
        echo &#39;World&#39;;
    }
}class MyHelloWorld {
    use Hello, World;    public function sayExclamationMark() {
        echo &#39;!&#39;;
    }
}$o = new MyHelloWorld();$o->sayHello();$o->sayWorld();$o->sayExclamationMark();//output: Hello World!?>

Naming Conflict

If two traits insert a method with the same name without explicitly resolving the conflict a fatal error will occur.

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 other methods to be excluded. 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.

<?phptrait A {    public function a() {
        echo &#39;a1&#39;;
    }    public function b() {
        echo &#39;a2&#39;;
    }
}trait B {    public function a() {
        echo &#39;b1&#39;;
    }    public function b() {
        echo &#39;b2&#39;;
    }
}class C {
    use A, B {        B::a insteadof A;//insteadof 指定B类中的a方法在A类中,以解决命名冲突
        B::b insteadof A;
        A::a as a1;//把A类中的a方法取别名为a1,以解决命名冲突
        A::B as a2;
    }
}$C = new C();$C -> a();//b1$C -> b();//b2$C -> a1();//a1$C -> a2();//a2?>

as You can also modify the access control of the method

Example #6 修改方法的访问控制<?php
    trait Hello {        public function traitHello() {
            echo "hello,trait\n";
        }
    }    // 修改 traitHello 的访问控制
    class Class1 {
        use Hello {            traitHello as protected;
        }
    }    // 给方法一个访问控制的别名,原版 traitHello 的访问控制则没有发生变化
    class Class2 {
        use Hello {            Hello::traitHello as private hi;
        }
    }    $Obj1 = new Class1();    // $Obj1->traitHello(); # 报致命错误,因为traitHello方法被修改成受保护的
    $Obj2 = new Class2();    $Obj2->traitHello(); # 原来的traitHello方法仍然是公共的
    // $Obj2->hi();  # 报致命错误,因为别名hi方法被修改成私有的

Trait can also be combined Trait

Trait supports abstract methods, static attributes and static methods

<?phptrait Hello {    public function sayHello() {
        echo "Hello\n";
    }
}trait World {    use Hello;    public function sayWorld() {
        echo "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;get World&#39;;
    }
}$Obj = new HelloWorld();$Obj->sayHello();//Hello$Obj->sayWorld();//Worldecho $Obj->getWorld() . "\n";////get WorldHelloWorld::doSomething();//Doing something$Obj->inc();//1$Obj->inc();//2

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.

Example #12 解决冲突<?phptrait PropertiesTrait {    public $same = true;    public $different = false;
}class PropertiesExample {
    use PropertiesTrait;    public $same = true; // PHP 7.0.0 后没问题,之前版本是 E_STRICT 提醒
    public $different = true; // 致命错误}?>

Related recommendations:

[php classes and objects]Final keyword

[php classes and objects]late static binding

[php classes and objects] type constraints

The above is the detailed content of [php classes and objects] trait. For more information, please follow other related articles on the PHP Chinese website!

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool