norbert23
norbert23

Reputation: 73

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?

Upvotes: 2

Views: 459

Answers (2)

abr
abr

Reputation: 2129

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

Upvotes: 2

Fobos
Fobos

Reputation: 1156

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!

Upvotes: 3

Related Questions