… or what you need to keep in mind when using DI (dependency injection).
Let’s think of an example: we have an application and want to use some generic counter object given to some of our objects. The counter might be counting MySQL queries for statistics purposes for example.
We create a counter object and an object of type testCounter that gets the counter as construction parameter. Then we increase the counts via cloneTesters class method and note, that our original counter object still is the same as the one inside the class and therefore also got updated.
We can give the same counter object to another instance of our cloneTester class and see, that wherever we increase the counter ( $oTestA or $oTestB), we always access the same counter object. So here we have a counter that can be used in more than one class and in the end gives us some overall count. That’s the way to see it positive. Be aware of this behavior, otherwise you might soon get some very unexpected results.
We get the same behavior when changing the cloneTester constructor to
So before reusing objects, think about what the desired behaviour is 😉