In OOP PHP witch is better to let a factory return, new instance or the same instance, when it comes to performance and unit testing.
Eg. is creating new instances each time a class is to be used considered bad practice?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You dont want to have Factories return the same instance. You want them to return new instances. That’s the point of a Factory. Singletons have no use in PHP. If you want to limit an instance to just one instance, then create it once and inject it where it is needed.
Performance-wise it is negligible whether you return the same instance or create a new one. That is, unless you are doing very costly work in the ctor (like connecting to a database), which you shouldnt anyway.
For unit-testing, you want your Factories to return fresh instances and not the same ones, because that would be global state. Test should happen in isolation and not with the state of some instance from a previous test still in place, because that is more error prone.