[php classes and objects] trait

不言
Release: 2023-03-24 08:36:01
Original
1745 people have browsed it


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!?>
Copy after login
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!?>
Copy after login

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!?>
Copy after login

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?>
Copy after login

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方法被修改成私有的
Copy after login

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

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; // 致命错误}?>
Copy after login

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!

Related labels:
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!