I need to modify some variables in the same way. For example I need to multiply each variable with 2 when some conditions met. Like this:
$a = 10;
$b = 100;
$c = 1000;
$d = 10000;
if($someCondition) {
$a *= 2;
$b *= 2;
$c *= 2;
$d *= 2;
}
Here I want to call a function to apply the change to all variables instead of multiplying one by one. I tried using a callback function like this (writing such function for this type of simple calculations may look silly, but I have more complex things to do, just keeping it simple here for better understanding):
Trial 1
function multiply_vars(&$a,&$b,&$c,&$d) {
foreach(func_get_args() as $val) {
$val *= 2;
}
}
if($someCondition) {
multiply_vars($a,$b,$c,$d);
}
This works, but I need to know exactly how many variables I am passing to the function and set each variable as reference with
&
. For example, the above function will give me incorrect result when I pass 5 variables to modify.
Trial 2
function multiply_vars() {
foreach(func_get_args() as $varname) {
global $$varname;
$$varname *= 2;
}
}
if($someCondition) {
modify_vars('a','b','c','d');
}
This works in a global context. But the problem is, I am doing this inside a class function where
global $$varname
refers to a variable outside my class function.
Is there any other way for achieving my purpose?
Note: I don't want to put my variables into an array. I know, it can be better solved by
array_map()
function, if it was in an array.