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

后端 未结 5 1930
时光说笑
时光说笑 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:55

    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
    

提交回复
热议问题