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.
Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
Overriding a trait function The trait function can be overridden simply by defining a function with the same name in the class.
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.
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.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With