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.
By 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.
The 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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With