LMSouq
php-dev Open

How to override trait function and call it from the overridden function?

SH
Shu
1 month ago
3 views
Problem Description
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 :)

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base