简体   繁体   中英

Extending a class with a trait

Since I've just jumped from another language to PHP, I would like to ask you what would be a correct way of adding an extension to a class. My config right now is as follows:

class A extends B {
    use C;         

    public function a(){

    }
}

I need to add some additional functions to class A, but logically divide them from it, so I though I would be using a trait C.

So my question is - can I use function a() in my trait C? I know I can define abstract function a() in trait C, however I believe that wouldn't be a good practice at all. Maybe I can somehow inject this into a trait or is it a bad practice as well?

It is possible, the choice is a discretion of the developer, the best solution is based on experience.

trait C {
    public function hello() {
        parent::a();
        echo 'World!';
    }
}

class B {
    function a() {
        echo "hello";
    }
}

class A extends B{
    use C;  
}

(new A())->hello(); // helloWorld!

Let's say:

Class B { 
    public function a () { 
    //Does something
    } 
}

Class A extends B { 
//We got access to B's public function. If you want to execute B's a and add some more content, then
    public function a() {
        parent::a();
        //Some more content
    }
}

Traits were developed due to PHP's nature of not allowing to inherit from multiple classes (Single inheritance). By creating a trait and apply it to a class, you know inherit it's methods

http://php.net/manual/en/language.oop5.traits.php

It really comes down to your needs.

Q: Do you want to create an interface and make other classes implement certain methods? A: Create an interface

Q: Do you want to create an abstract class with some implementations and allow other classes to use them? A: Create an abstract class

Q: Do you want a class to inherit from two other classes and they've got different functionalities? A: Create a trait

The best approach is to use the tools at your disposal in order to output your desired result and keeping it organized

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM