【问题标题】:How to define method chaining in PHP [duplicate]如何在 PHP 中定义方法链 [重复]
【发布时间】:2012-10-22 11:24:02
【问题描述】:

可能重复:
PHP method chaining?

我想使用组合功能,例如:

select("SELECT * FROM users").where("user=l0 ").join(" . . . ");

如何在php中定义这个?

【问题讨论】:

  • 我觉得我应该警告你,这种东西写起来比看起来要难很多。您给出的简单示例并不难实现,但也不会实现太多(您不妨将查询编写为字符串)。如果你想让它做任何聪明的事情,那将是一个非常大的项目。

标签: php


【解决方案1】:
function select(){
     ....
     return new myType;
}

class myType {

     function where(){
         ...
         return $this;
     }

     function join(){
         ...
         return $this;
     }

}

演示:http://codepad.org/pyrIEW0t

记得在 PHP 中使用-> 而不是.

这是一个 PHP 函数链的例子。

【讨论】:

  • @user1792423 除非您只是连接字符串(我认为您不想这样做),否则您不会这样做。
【解决方案2】:

该函数返回一个string,您可以连接多个函数的返回值。

function select($input) {

//process $input

return $output;

}

function where($input) {

//process $input

return $output;

}

在您的 php 中,您可以调用这些函数并获得串联的返回结果。

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 2017-12-21
    • 2012-03-11
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多