如何在PHP5中构建多oop函数 [英] How to build multi oop functions in PHP5
问题描述
我对PHP5中的OOP有疑问.我看到越来越多的代码是这样写的:
I have a question about OOP in PHP5. I have seen more and more code written like this:
$object->function()->first(array('str','str','str'))->second(array(1,2,3,4,5));
但是我不知道如何创建这种方法.希望有人可以在这里为我提供帮助,:0)非常感谢.
But I don't know how to create this method. I hope somebody can help me here, :0) thanks a lot.
推荐答案
在您自己的类中链接方法的关键是返回一个对象(几乎总是$this
),然后将该对象用作该对象的对象.下一个方法调用.
The key to chaining methods like that within your own classes is to return an object (almost always $this
), which then gets used as the object for the next method call.
像这样:
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(...);
的一种较短方法,它消除了调用后不再使用的设置变量的丑陋性.
Note, it's possible to return an object other than $this
, and the chaining stuff above is really just a shorter way to say $a = $obj->first(...); $b = $a->second(...);
, minus the ugliness of setting variables you'll never use again after the call.
这篇关于如何在PHP5中构建多oop函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!