如何在 PHP5 中构建多 oop 函数
我有一个关于 PHP5 中的 OOP 的问题。我看到越来越多的代码是这样写的:
$object->function()->first(array('str','str','str'))->second(array(1,2,3,4,5));
但我不知道如何创建这个方法。我希望有人能在这里帮助我,:0) 非常感谢。
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));
But I don't know how to create this method. I hope somebody can help me here, :0) thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您自己的类中链接此类方法的关键是返回一个对象(几乎总是
$this
),然后将该对象用作下一个方法调用的对象。就像这样:
注意,可以返回
$this
以外的对象,上面的链接实际上只是表示$a = $obj->first(. ..); $b = $a->second(...);
,减去设置调用后永远不会再使用的变量的丑陋。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.Like so:
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.这不是严格有效的 PHP,但这说明的是...您正在调用 $object 类上的方法,该方法本身返回一个对象,您在该对象中调用名为
first()
的方法它还返回一个对象,您在该对象中调用名为second()
的方法。因此,这不一定只是一个具有一种方法的类(尽管可能是),而是一系列可能不同的类。
像这样的东西:
This isn't strictly valid PHP, but what this is saying is... You are calling a method on the $object class that itself returns an object in which you are calling a method called
first()
which also returns an object in which you are calling a method calledsecond()
.So, this isn't necessarily just one class (although it could be) with one method, this is a whole series of possibly different classes.
Something like: