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

后端 未结 5 1945
时光说笑
时光说笑 2020-11-27 09:49

Scenario:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    use A;

    function calc($v) {
        $v++;
        return A:         


        
5条回答
  •  再見小時候
    2020-11-27 09:56

    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...

提交回复
热议问题