Still on the PHP-OOP training wheels, this question may belong on failblog.org. =)
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开发者_如何学JAVA')->set('admin')->render();
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?
Do I have that right?
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.
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.
精彩评论