I normally use procedural programming with PHP and looking at other questions here asking how to avoid globals the answers were often to use OOP instead. Is it not possible to avoid globals with procedural programming?
For example I can write the following function in two ways. Both have advantages and disadvantages. If I call this function often then it looks bloated with the second method since it has to pass all the variables each time. The alternative is the first method where the function simply passes the value and the variables are all globals in the function.
doWhatIneedtodo(2);
function doWhatIneedtodo($val) {
global $this; global $that; global $theother;
if ($val == 1) {
$this++;
} else
if ($val == 2) {
$that++;
} else
if ($val == 3) {
$theother++;
}
}
doWhatIneedtodo(2,$this,$that,$theother);
function doWhatIneedtodo($val,&$this,&$that,&$theother) {
if ($val == 1) {
$this++;
} else
if ($val == 2) {
$that++;
} else
if ($val == 3) {
$theother++;
}
}
Or perhaps there's a better way to do this that I haven't though of?
The reason you mostly find answers regarding this question for OOP is twofold I think:
Apart from that, my preference goes to your second implementation because it would be far more easy to transition this into proper OOP code. If you use the first implementation and you'd want to change the names of the variables, you'd have to adjust the calling code and the function itself.
It's very much a progression from troublesome code to less troublesome code:
So you see, solving problems with global procedural code one by one eventually leads to OOP anyway, at least in PHP. There's a fork in the road halfway through where you could go to pure functional programming as well, but PHP is ill-equipped for being a purely functional language.