为什么我的方法链不起作用?

Sho*_*291 0 php methods chaining

我正在尝试编写一个显示错误的类。我希望能够在一条线上完成。所以这就是我用来显示错误的内容:

$this->error->title("Error Title")->message("This is an error message")->redirect('home')->display();
Run Code Online (Sandbox Code Playgroud)

这是我的课:

<?php

class Error {

    var $title;
    var $message;
    var $redirect;

    function title($title){

        $this->title = $title;

    }

    function message($message){

        $this->message = $message;

    }

    function redirect($redirect){

        $this->redirect = $redirect;

    }

    function display(){

        $CI &= get_instance();

        $CI->template->overall_header($this->title);

        $data = array(
            'error_title' => $this->title,
            'error_message' => $this->message
            );

        if(isset($this->redirect)){

            $data['redirect'] = $this->redirect;

        }

        $CI->load->view('error_body', $data);

    }

}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

 Fatal error: Call to a member function message() on a non-object in ...\application\frontend\controllers\members\login.php on line 128 
Run Code Online (Sandbox Code Playgroud)

为什么我会在 message() 方法上而不是在 title 方法上收到错误?

Bli*_*itZ 5

方法链需要你把

return $this;
Run Code Online (Sandbox Code Playgroud)

在可链接方法的末尾。

为什么我会在 message() 方法上而不是在 title 方法上收到错误?

因为你的第一条链调用returnsnullnon-object

$this->error->title("Error Title")->message("This is an error message")->redirect('home')->display();
//            ^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

虽然定义是:

function title($title){
    $this->title = $title;
} // return value not specified, so it returns null
Run Code Online (Sandbox Code Playgroud)

你如何解决它?尝试这个:

function title($title){
    $this->title = $title;
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

等等。我希望你想通了。