If I do this in PHP 5.x (generally pseudo-code):
class object{
__construct($id){
<<perform database query>>
}
}
$array(1) = new object(1);
$array(1) = new object(1);
Am I wasting efforts (memory, cpu, etc)? Will the database query run twice?
What is the best way to avoid this (if it’s a concern)? Using $array(1) instanceof object? isset($array(1))? array_key_exists(1, $array)?
Is there a (good?) way to check in the class to see if it already exists before it does all the work again?
EDIT: For clarity, I do not need this object twice. And this object will be used again $array(523) = new object(523); My main question is how best to avoid redundantly creating the exact same object.
If you want to avoid creating multiple objects, you have a few choices. The ones that come to mind are…
Create the object once and ensure it’s passed to where it’s needed. This means you’ll have to check the dependencies in your code with respect to that object.
Use an object factory to construct the object and it can return a reference to the object rather than creating a new one, if it was already created.
Implement the singleton pattern.
As with everything else, trade-offs obtain, so check your situation and decide what is the most appropriate for you.