The following PHP example code only works if the “bar” elements come before the “foo” elements. If they are in the wrong order, I will get a “call to a member function on a non-object” error.
$data = array();
foreach($elems as $e) {
if($e['type'] == "foo") {
$data[$e["key"]->foo_data($e["data_foo"]);
}
elseif($e['type'] == "bar") {
$data[$e["key"]] = new Bar($e);
}
}
My solution at the moment is to iterate twice through $elems. Another solution would be to use usort with a custom sort function that puts “bar” elements before “foo” elements.
Are there any programming patterns or libraries that would allow me to process the elements in arbitrary order?
Looping twice seems like the most sensible solution. Loop once to prepare your objects, loop a second time to let those objects process data. There may be an entirely different, better solution, but that’s hard to say without seeing a more concrete use case.