PHP method chaining benefits?

孤人 提交于 2019-12-01 21:02:02

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();

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.

It still instantiates an object; it's just never assigned to a variable. Basically, you're just calling the methods of an anonymous object.

I think any cycle-savings would be negligible, but I think the unassigned objects would be freed immediately after this line of code, so you may have some memory savings (you could accomplish the same by setting assigned objects to null when you were done with them).

The main reason people use method chaining is for convenience; you're doing a lot in one line of code. Personally, I think it's messy and unmaintainable.

AntonioCS

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?

Wrong! To return $this, the class has to be instantiated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!