I'm talking about methods like this:
$object->method()->method1('param')->method2('param');
Those are created by returning the object in the function.
return $this;
I've seen third-party software use that method, but I'm wondering, wouldn't that cause a bit of a problem with the resources or memory because you're continuously returning the entire object?
You are not returning the entire object, but rather a reference to the object -- that is, just the memory location where it resides. So objects aren't constantly being copied around in memory when methods are called along the chain.
ReplyDeleteBy default (mainly, but read the link for actual details), objects in PHP are passed, returned, and assigned by reference.
See the PHP docs on references.
Chaining methods by returning the object is actually efficient.
ReplyDeleteThe stack does not grow bigger by adding new methods to the chain.
PHP also does not return a copy of the object but a reference, it does not pass the object but a "pointer".
Those aren't "nested methods", but it's called method chaining and it shouldn't affect performance in anyway (your not going anyhow "deep in the stack").
ReplyDeleteYou can split the code into those pieces:
$res = $object->method();
$res = $res->method1('param')
$res = $res->method2('param');
// and res is still equivalent to $object if you return $this
So no object copying, no nested calls, no many items in "call stack"... No performance overhead, you should be just fine.