PHP方法链接的好处? [英] PHP method chaining benefits?

查看:80
本文介绍了PHP方法链接的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍然在PHP-OOP培训轮上,此问题可能属于 failblog.org . =)

Still on the PHP-OOP training wheels, this question may belong on failblog.org. =)

PHP中的方法链接有什么好处?

What are the benefits of method chaining in PHP?

我不确定这是否重要,但是我将静态地调用我的方法.例如

I'm not sure if this is important, but I'll be calling my method statically. e.g.

$foo = Bar::get('sysop')->set('admin')->render();

根据我的阅读,允许返回$this的任何方法都可以链接.我刚刚了解到这是PHP5中的新功能.在我看来,如果我不必实例化一个新对象(静态地调用它)而只从类中选择一些我需要的方法,那么可能会带来速度上的好处?

From what I've read, any method which returns $this is allowed to be chained. I just learned this is new in PHP5. Seems to me there may be speed benefits if I don't have to instantiate a whole new object (calling it statically) and just select the few methods I need from the class?

我有那个权利吗?

推荐答案

使用这两种方法都没有明显的性能优势,尤其是在具有字节码缓存的生产服务器上.

There are no significant performance benefits to using either approach, especially on a production server with byte code cache.

方法链接只是编写事物的一种较短的方法.与较长版本进行比较:

Method chaining is just a shorter way of writing things. Compare with the longer version:

$foo = Bar::get('sysop');
$foo -> set('admin');
$foo -> render();

它确实有一些古怪之处:典型的IDE(例如Eclipse)可以在较长版本中自动完成代码(只要知道$foo的类型),但是需要您记录返回类型简短版本中可用的所有方法.

It does have some quirks, though: a typical IDE (such as Eclipse) can auto-complete your code in the longer version (as long as the type of $foo is known) but needs you to document the return type of all methods to work in the short version.

这篇关于PHP方法链接的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆