Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using method chaining in PHP cause any problems with resources or memory?

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?

like image 820
Zerbu Avatar asked Sep 05 '26 04:09

Zerbu


2 Answers

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.

like image 86
Michael Berkowski Avatar answered Sep 07 '26 18:09

Michael Berkowski


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".

like image 22
Martin Samson Avatar answered Sep 07 '26 17:09

Martin Samson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!