I have the code below that in the case of function ‘test’ works as required, while when the work of ‘foreach’ is factored into a function things stop working as variables go out of scope. Is there a way to maintain them in scope while being able to factor the code as a function?
function test()
{
$a = 'aaa';
$b = 'bbb';
$c = 'ccc';
$A = ['a', 'b', 'c'];
foreach ($A as $_a) $r[$_a] = $$_a;
var_dump($r);
}
// running test() gives ['a'=>'aaa','b'=>'bbb','c'=>'ccc']
function KV($A)
{
foreach ($A as $_a) $r[$_a] = $$_a;
return $r;
}
function test1()
{
$a = 'aaa';
$b = 'bbb';
$c = 'ccc';
$A = ['a', 'b', 'c'];
$r = KV($A);
var_dump($r);
}
running test1() gives ['a'=>NULL,'b'=>NULL,'c'=>NULL]
comment: the looping variable has been named ‘_a’ in order to avoid name clashes with possible variable names.
just to understand the usefulness of the need, I write bellow a real case where the function would be used.
$r = [
'series' => $series,
'aa' => $aa,
'issueDate' => $issueDate,
'invoiceType' => $invoiceType,
'vatPaymentSuspension' => $vatPaymentSuspension,
'currency' => $currency,
'exchangeRate' => $exchangeRate,
];
if ($correlatedInvoices) {
$r['correlatedInvoices'] = $correlatedInvoices;
}
if ($selfPricing) {
$r['selfPricing'] = $selfPricing;
}
3
Answers
It seems that actually there is no way to do it,so I present the solution I devised to do the same bypassing the lack of options. By the way I suggest to the language designer to provide a bidimensional array like $LOCALS where we can access values of previous calls as
$LOCALS[-1]['nameOfLocalInCallingFunction']
or something similar ($LOCALS[1])The solution bellow seems the best option available to obtain the scope at hand:
You can pass the array by reference to be able to update within the function’s scope.
You can give all variables defined to your function with
get_defined_vars()
https://www.php.net/manual/en/function.get-defined-vars.phpor