Search code examples
phpmethodschaining

Why is my method chaining not working?


I am trying to write a class that displays errors. I would like to be able to do it on one line. So this is what I use to display the error:

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

This is my class:

<?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);

    }

}

This is the error that I am getting:

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

Why would I get the error on the message() method but not on the title method?


Solution

  • Method chaining requires you to put

    return $this;
    

    in the end of chainable methods.

    Why would I get the error on the message() method but not on the title method?

    Because your firsh chain call returns null or non-object:

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

    While definition was:

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

    How do you fix it? Try this:

    function title($title){
        $this->title = $title;
        return $this;
    }
    

    And so on. I hope you figured out.