The Prototype design pattern allows us to effectively duplicate objects while minimizing the performance impacts of having to re-instantiate an object.
You may have heard of prototypal languages if you've worked with JavaScript. In such languages, you work by cloning prototypal objects to create new objects; in turn, there is a reduced cost for creating new objects.
We have, so far, extensively discussed the use of the __construct magic
method, but we haven't touched on the __clone magic
method. The __clone magic
method is what's run before an object is cloned (if possible); the method cannot be called directly and takes no parameters.
You might find it useful to use the __clone
method when using this design pattern; that said, you might not need it depending on your use-case.
It's very important to remember that when we clone an object, the __construct
function is not re-run. The object has already been constructed so PHP sees no reason to re-run it, so it's worth avoiding...