Recursive function referenced collection
I'm trying to generate a collection using recursive logic by populating a referenced arra开发者_如何学Goy, but I'm not that steady on the referenced syntax. Does the below example make sense? (Have I understood how to correctly use this operator?) If not, how to accomplish this?
// I want all uniquely named subfolders returned as array
$allFolders = recursive('/');
function recursive($folder,$collection=array())
{
/* Look up direct children here */
foreach ($subFolders as $folder) {
if (!isset($collection[$folder])) {
$collection[$folder] = $folder;
recursive($folder,&$collection);
}
}
return $collection;
}
You need to declare "by reference" in the function definition - and default value is rather useless, since you won't be able to access it after the function completes. You should have it like this:
$folder = '/';
$collection = array();
recursive($folder, $collection);
print_r($collection);
function recursive($folder, &$collection)
{
...
}
While PHP5 will accept a default value for a by-reference argument, it makes very little sense.
You also should not use the "by reference" in the call:
recursive($folder, $collection);
While the second (by reference in the call) was allowed in earlier versions of PHP, it's been deprecated.
精彩评论