Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to extend a trait in PHP?

I want to use functionality of an existing trait and create my own trait on top of it only to later apply it on classes.

I want to extend Laravel SoftDeletes trait to make SaveWithHistory function, so it will create a copy of a record as a deleted record. I also want to extend it with record_made_by_user_id field.

like image 385
Yevgeniy Afanasyev Avatar asked Oct 28 '16 06:10

Yevgeniy Afanasyev


People also ask

Can traits be extended?

Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.

How do you override a trait?

Overriding a trait function The trait function can be overridden simply by defining a function with the same name in the class.

Can PHP traits have properties?

Traits can have properties and methods with private and protected visibility too. You can access them like they belong to class itself. There is no difference.

Can a trait have a constructor PHP?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.


1 Answers

Yes, there is. You just have to define new trait like this:

trait MySoftDeletes  {     use SoftDeletes {         SoftDeletes::saveWithHistory as parentSaveWithHistory;     }      public function saveWithHistory() {         $this->parentSaveWithHistory();          //your implementation     } } 
like image 129
Filip Koblański Avatar answered Sep 22 '22 17:09

Filip Koblański