Extend Traits with Classes in PHP?

后端 未结 3 1451
萌比男神i
萌比男神i 2020-12-29 19:59

Why we are not allowed to extend Traits with Classes in PHP?

For example:

Trait T { }

Class C use T {}
/*          


        
3条回答
  •  死守一世寂寞
    2020-12-29 20:07

    You can extend traits somewhat. Expanding on mrlee's answer, when you use a trait you can rename its methods.

    Say for example you have a "parent" trait that was defined by your framework:

    trait FrameworkTrait {
        public function keepMe() {
            // Framework's logic that you want to keep
        }
    
        public function replaceMe() {
            // Framework's logic that you need to overwrite
        }
    }
    

    Simply pull in the parent trait, rename its replaceMe method to something else, and define your own replaceMe method.

    trait MyTrait {
        use FrameworkTrait {
            FrameworkTrait::replaceMe as frameworkReplaceMe;
        }
    
        public function replaceMe() {
            // You can even call the "parent" method if you'd like:
            $this->frameworkReplaceMe();
    
            // Your logic here
        }
    }
    

    And then in your class:

    class MyClass {
        use MyTrait;
    }
    

    Now objects of this class can do this:

    $obj = new MyClass();
    
    $obj->keepMe();             // calls "parent" trait
    $obj->replaceMe();          // calls "child" trait
    $obj->frameworkReplaceMe(); // calls "parent" trait
    

提交回复
热议问题