What does “return $this” mean?

前端 未结 7 451
遇见更好的自我
遇见更好的自我 2020-12-13 00:34

I\'m trying to understand this code, and when I arrived at the final line, I didn\'t get it. :(

Can I have your help in order to find out, what does re

7条回答
  •  鱼传尺愫
    2020-12-13 01:12

    Its a common OOP technique called Fluent Interface. It main purpose to help chain multiple method calls in languages, that do not support method cascading, like PHP. So

    return $this;

    will return an updated instance(object) of that class so it can make another call in its scope. See example in PHP,

    class Class_Name {
        private field1;
        private field2;
        private field3;
    
        public function setField1($value){
    
            $this->field1 = $value;
    
            return $this; 
        }
    
        public function setField2($value){
    
            $this->field2 = $value;
    
            return $this; 
        }
    
        public function setField3($value){
    
            $this->field3 = $value;
    
            return $this; 
        }
    } 
    
    $object = new Class_Name();
    $object->setField1($value1)->setField2($value2)->setField3($value3);
    

提交回复
热议问题