2

我对 PHP5 中的 OOP 有疑问。我看到越来越多的代码是这样写的:

$object->function()->first(array('str','str','str'))->second(array(1,2,3,4,5));

但我不知道如何创建这个方法。我希望有人可以在这里帮助我,:0) 非常感谢。

4

2 回答 2

8

在您自己的类中链接此类方法的关键是返回一个对象(几乎总是$this),然后将其用作下一个方法调用的对象。

像这样:

class example
{
    public function a_function()
    {
         return $this;
    }

    public function first($some_array)
    {
         // do some stuff with $some_array, then...
         return $this;
    }
    public function second($some_other_array)
    {
         // do some stuff
         return $this;
    }
}

$obj = new example();
$obj->a_function()->first(array('str', 'str', 'str'))->second(array(1, 2, 3, 4, 5));

请注意,可以返回除 之外的对象$this,并且上面的链接内容实际上只是一种更简短的说法$a = $obj->first(...); $b = $a->second(...);,减去设置变量的丑陋,您在调用后将永远不会再使用。

于 2010-07-21T11:31:47.517 回答
0
$object->function()->first(array('str','str','str'))->secound(array(1,2,3,4,5));

这不是严格有效的 PHP,但它的意思是......您正在调用 $object 类上的一个方法,该方法本身返回一个对象,在该对象中您正在调用一个被调用的方法,该方法first()还返回一个您正在调用的对象一种称为second().

所以,这不一定只是一个类(尽管它可能是)一个方法,这是一系列可能不同的类。

就像是:

class AnotherClass {
    public function AnotherClassMethod() {
        return 'Hello World';
    }
}

class MyClass {
    public function MyClassMethod() {
        return new AnotherClass();
    }
}

$object = new MyClass();
echo $object->MyClassMethod()->AnotherClassMethod();  // Hello World
于 2010-07-21T11:48:28.643 回答