【问题标题】:call 2 functions inside same class with the same entry使用相同的条目在同一类中调用 2 个函数
【发布时间】:2014-07-08 03:40:06
【问题描述】:

假设我有这个功能

class xx {
    function one() {
        echo "hello";
    }
    function two() {
        echo "how are you";
    }
}

如果我这样做

$call = new xx;
$call->one();

这将在页面上打印 hello 但是如果我想打印你好,我该怎么做呢?

$call->one()->two();

???因为我试过了,它只打印我你好,我怎样才能只用一句话来调用第二个函数? 也试过了

$call = new xx();
$calboth = $call->one();

$callboth->two();

但无论如何都只是打印你好,那我该怎么做呢?打印两个? 我的意思不是打印,而是让 2 个函数在同一个调用中工作

例如函数 dbconnect and login 或 dbconnect and register,在同一个类中 并在主文件中包含类 php 并仅使用我之前所说的内容调用

$login = new system;
$login->dbconnect()->login();

感谢所有的遮阳篷

【问题讨论】:

  • 第一个提示:$call->one()->two() 是一个等价于这个的表达式:$tmp = $call->one(); $tmp->two(); 大概$tmpnull 并且null 没有定义方法two()。跨度>

标签: php function class


【解决方案1】:

要链接方法,你需要返回一个类的实例:

class xx {
    function one() {
        echo "hello";
        return $this;
    }
    function two() {
        echo "how are you";
        return $this;
    }
}

那么这应该可以工作:

$call = new xx;
$call->one()->two();

【讨论】:

    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多