Basically my setup is that I have a lot of objects that I want to create. What type of object it will become is dependent on one variable, which is the type. So originally I would have to do many if statements, so to shorten it I created an array, but I am running in to the problem of being able to create the actual object through the array.
Here is what I had originally:
if($object->type = 'text')
{
$object_new = new Text();
} elseif($object->type = 'image') {
$object_new = new Image();
} ....
But what I wanted to do is:
$all_objects = array('text'=> new Text(), 'image' => new Image(), ...);
$object_new = $all_objects($object->type);
Which would shorten my code by a lot as well as make it more efficient.
If there is no further dependencies to these object, you can simply do
If you need more sophisticated creation logic, you can put the creation code in Lambdas and call those then, e.g.
Or you create a Factory object and put a switch/case into it:
Also checkout Is there a call_user_func() equivalent to create a new class instance?