代码之家  ›  专栏  ›  技术社区  ›  Kerry Jones

如何创建PHP方法链接?

  •  2
  • Kerry Jones  · 技术社区  · 16 年前

    我还看到过其他物体:

    $obj->method1()->method2();
    

    我该怎么做?每个函数只是修改一个对象的指针还是返回一个指针?

    我不知道这种风格的恰当术语——如果有人能帮我,那就太好了。

    4 回复  |  直到 16 年前
        1
  •  5
  •   Lotus Notes    16 年前

    这是通过返回来实现的 $this 在每个函数的末尾,从而给出一个可链接的引用。

    class MyClass {
        public function method1() {
            //...
            return $this;
        }
        public function method2() {
            //...
            return $this;
        }
    }
    
        2
  •  4
  •   Mark Baker    16 年前

    流体界面。

    只需设置对象的method1()返回$this

        3
  •  1
  •   ronaldosantana    16 年前

    假设你有个人课。你的方法是这样的:

    public function setName($name)
    {
        $this->name = $name;
        return $this; // We now return $this (the Person)
    }
    

    下载Zend框架并检查代码的某些部分—您可以从中学到很多东西。

        4
  •  1
  •   dalton    16 年前

    我称之为方法链接。见 http://www.devshed.com/c/a/PHP/Method-Chaining-in-PHP-5/1/

    也在你的方法里面

    public function method1()
       // do stuff
    
       return $this;
    }
    
    推荐文章