在进行递归调用时,有没有办法保存变量的值? $ totalNumResources和$ totalSize会发生什么?
我希望PHP保存一旦start函数从递归调用返回时将返回的变量。我不希望将其修改为参数。
这与问题here不重复。
function start($URL) {
if (!check_if_html($URL)) {
$totalSize = get_remote_file_size($URL);
echo "Download Size: $totalSize Bytes ";
$totalNumResources += 1; //single resource is an HTTP request
echo "HTTP requests: $totalNumResources";
return;
}
$totalNumResources += 1;
foreach ($html->find('iframe') as $element) {
echo "IFRAME" . "$element->src.\n";
start($element->src);
}
}
答案 0 :(得分:1)
$totalNumResources
和$totalSize
是函数中的局部变量,因此它们存在于功能块中。当您的函数以递归方式调用时,新函数调用将创建具有相同名称的变量并将其初始化。目前还不清楚你打算用递归$totalSize
做什么,但是如果你想知道$totalNumResources
的值,你可以修改它作为参数,如下所示:
function start($URL, $totalNumResources = 0) {
if (!check_if_html($URL)) {
$totalSize = get_remote_file_size($URL);
echo "Download Size: $totalSize Bytes ";
$totalNumResources += 1; //single resource is an HTTP request
echo "HTTP requests: $totalNumResources";
return;
}
$totalNumResources += 1;
foreach ($html->find('iframe') as $element) {
echo "IFRAME" . "$element->src.\n";
$totalNumResources += start($element->src, $totalNumResources);
}
return $totalNumResources;
}