Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

class

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

$foo = $wke->template->notify()
                     ->type("ERROR")
                     ->errno("0x14")
                     ->msg("You are not logged.")
                     ->page("login.tpl");

In the end, I need my $foo variable will return this:

$foo->type = "ERROR" 
$foo->errno= "0x14" 
$foo->msg= "You are not logged." 
$foo->page= "login.tpl"

Please note that the $wke->template is where i need call the notify() element.

like image 829
DrSAS Avatar asked Jul 19 '12 02:07

DrSAS


2 Answers

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;

like image 166
Rajan Rawal Avatar answered Oct 08 '22 04:10

Rajan Rawal


Each of those methods will need to return some object that stores what you set as the argument in it. Presumably, it will be the template that contains each object property on it, and when you call the method it sets that corresponding variable and returns itself.

like image 36
jprofitt Avatar answered Oct 08 '22 06:10

jprofitt