本文介绍了如何在同一行中对类方法进行多次调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP有一个问题。
在我的php文件中,我创建了以下行:

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

最后,我需要我的 $ foo variable will return This:

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"

请注意, code> $ wke-> template 是我需要调用 notify()元素。

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

推荐答案

通过 - >调用类一的函数的方法,因为函数返回类的同一个对象。请参见下面的示例。你会得到这个

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;
    }
}

整个魔法是 return $ this;

这篇关于如何在同一行中对类方法进行多次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 11:36