Would this method
foreach($data as &$d)
$obj[]=ClassName::createObject($data);
or
foreach($data as &$d){
$obj[] = new ClassName;
$obj[end($obj)]->loadData($data);
}
–
class ClassName{
public static function createObject($data){
$obj = new ClassName;
//do stuff with $data
return $obj;
}
public function loadData($data){
//do stuff with $data;
}
}
The ::createObject method makes for code which is a lot less painful to read while the second method doesn’t have to return huge objects.
I’m not sure how variables are handled in a language like PHP so is there a big difference in performance?
Which method would be best to use?
First looks ok. You don’t need to pass
$dby reference in this case. And probably you wantClassName::createObject($d). Still I’d refactor it to:This is just ugly, not for performance reasons:
Instead you could do this:
If the data is essential for the object – set it from the construct. If the data is optional, then the
loadDatamethod makes sense. But if you want to move the construct logic to a static method – this is pointless. No performance advantage.