Scenario:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return A:
Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.
This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.
trait A {
protected function traitcalc($v) {
return $v+1;
}
function calc($v) {
return $this->traitcalc($v);
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return $this->traitcalc($v);
}
}
class MyOtherClass {
use A;
}
print (new MyClass())->calc(2); // will print 4
print (new MyOtherClass())->calc(2); // will print 3