Clone wars …

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

Two example classes, first a simple counter:
And here the test class:
clone tester

First test:
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.
example 001

Second test:
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.
clone example 002
We get the same behavior when changing the cloneTester constructor to
clone tester construct 001

Third test:
If we want to make sure we have one counter object per cloneTester instance, we need to change the class constructor to use the clone() command.
clone tester construct 002

Here we get the answer:
clone example 003

So before reusing objects, think about what the desired behaviour is 😉

This entry was posted in PHP and tagged , , . Bookmark the permalink.

Leave a Reply