Reputation: 3158
Context: Two functions processing xml data that needs to be combined into a single array.
I am processing from multiple feeds and combining it into a multilevel associative array, like so:
$processedData:
Array (
[item1] => Array (
[somedata] => tasty
[moredata] => food
[evenmore] => like pizza
)
[item2] => Array (
[somedata] => less tasty
[moredata] => food
[evenmore] => like bread pudding
)
Each function is operating on separate data, and each gives me some of the data I need; for example, somedata
and moredata
come from function one
, while evenmore
comes from function two
.
function one ($xml) {
$myPrice = new XMLReader(); //some happy XMLReader stuff that works
$myPrice->xml($xml);
$key = '';
while ($myPrice->read()) {
if ($myPrice->nodeType == XMLReader::ELEMENT) { //only opening tags.
$tag = $myPrice->name;
switch ($tag) {
case 'TheKey':
$key = $myPrice->readInnerXML();
break;
case 'HowGood':
$processedData[$key]['somedata'] = $myPrice->readInnerXML();
break;
case 'TypeOfThing':
$processedData[$key]['moredata'] = $myPrice->readInnerXML();
break;
}
}
}
}
Function two
is structurally similar, but processes different data. Both functions should ideally return their data into one array. This can be easily accomplished by declaring global $processedData
near the top of each function. Combining the return values with array_merge
and +
will overwrite values with the same key, according to the php manual.
Note: unlike most other questions about globals, the issue is not the input values, but the output values.
The question Are global variables in PHP considered bad practice? If so, why? suggests clearly labeling global variables to solve the common issues with global variables, but pretty much every answer on stack overflow re:Global Vars in PHP says "you can do this, but you probably shouldn't."
Is combining return values from multiple functions a good use of php globals? Is there a way to do this avoiding global variables?
Or, alternatively, what cases are a good use of php globals? When are global variables good to use?
Upvotes: 0
Views: 122
Reputation: 15464
You could pass your variable as second argument using reference.
function one($xml, &$processedData){}
function two($xml, &$processedData){}
It helps you to avoid using global.
http://php.net/manual/en/functions.arguments.php#functions.arguments.by-reference
Upvotes: 1