Scenario:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return A::calc($v);
}
}
print (new MyClass())->calc(2); // should print 4
This code doesn't work, and I cannot find a way to call a trait function like it was inherited. I tried calling self::calc($v)
, static::calc($v)
, parent::calc($v)
, A::calc($v)
and the following:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A {
calc as traitcalc;
}
function calc($v) {
$v++;
return traitcalc($v);
}
}
Nothing works.
Is there a way to make it work or must I override completely the trait function which is much more complex than this :)
Your last one was almost there:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A {
calc as protected traitcalc;
}
function calc($v) {
$v++;
return $this->traitcalc($v);
}
}
The trait is not a class. You can't access its members directly. It's basically just automated copy and paste...