How to make multiple calls to class methods in the same line?

前端 未结 2 1101
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 12:10

I have an issue in PHP. In my php file, i created the following line:

$foo = $wke->template->notify()
                     ->type(\"ERROR\")
                    


        
2条回答
  •  长情又很酷
    2021-02-19 12:34

    The way of calling function of class one by one just by "->" because the function returning the same object of the class. See the example below. You will get this

    class Wke {
    
        public $type;
        public $errno;
        public $msg;
        public $page;
    
        public $template = $this;
    
        public function notify(){
            return $this;
        }
    
        public function errorno($error){
            $this->errno = $error;
            return $this; // returning same object so you can call the another function in sequence by just ->
        }
        public function type($type){
            $this->type = $type;
            return $this;
        }
        public function msg($msg){
            $this->msg = $msg;
            return $this;
        }
        public function page($page){
            $this->page = $page;
            return $this;
        }
    }
    

    The whole magic is of return $this;

提交回复
热议问题