I have to transfer a lot of old procedural code to OOP in Laravel.
In this code there are hundreds of dynamically-generated arrays, which come form many nested if
s, foreach
s etc.
Vanilla PHP doesn’t complain and gives only a notice, but Laravel throws an error for this:
$arr[$month][$year][$bla][$blablbalba] += $v;
The problem is in +=
.
Of course I can easily solve this problem with:
if (! isset($blabla)) {
// set it
}
The problem is that there are more than 250 arrays generated, and I don’t want to write 250 if
s.
I tried to use the magic methods __get()
and __set()
, but there is an issue with the __set()
method when you try something as:
$this->someProperty['key1']['key2']
Getting “Indirect modification of overloaded property” message.
This is more PHP-specific problem, it’s not much Laravel-related, but Laravel in my case is the barrier that shows this bad practice in the old code and throws and error.
How can I solve this problem, without writing if
s like crazy? Just want to mention one more time that the arrays are dynamically-generated and differently nested, depending on conditional logic. I can’t define all of them in the beginning of the methods of the class.
Is there a clever way to do it, or the business logic of the code has to be completely changed (very bad scenario)? Thank you in advance. I appreciate the time devoted.
Here is one of the many foreach
loops where these arrays are generated:
$heating_appliances = $haClass->calculateHA($scenario, $house_type, $year, $hd, $has, $ha_rp, $ha_dhp, $ha_chp, 'total_month', $extra_devices, $options);
foreach($heating_appliances[$year[0]] as $month => $classes) {
foreach($classes as $class => $energy) {
if(count(array_intersect($extra_devices, $groupsData[$class]['devices']))) {
if($group_type == 'total_co2') {
$profiles[$month][$class] += round((($energy * $co2[$class]) / 1000) * $energy_factor[$class], 3);
} else {
$profiles[$month][$class] += round($energy * $energy_factor[$class], 3);
}
}
}
}