PHP递归,递归跳出,递归结束,递归终止

原创
小哥 2年前 (2023-05-16) 阅读数 100 #大杂烩

PHP执行递归,以及在指定的位置跳出递归,即结束整个递归程序

//递归函数:查找路径下的php文件返回的数组是否包含键test
private $route;
private $method = test;
private function getRoute(string $path)
{
    static $quit = false;//变量$quit必须有静态符static修饰,否则‘跳出递归’无效
    $content = scandir($path);//返回文件名称数组,且以文件名排序的
    foreach ($content as $item) {
        if ($quit) {
            return;//跳出递归
        }
        if ($item == . || $item == ..) {
            continue;
        }
        if (is_file($path . / . $item)) {
            $routeArr = include $path . / . $item . ;
            if (isset($routeArr[$this->method])) {
                //找到目标文件
                $this->route = $routeArr[$this->method];
                $quit = true;
                return;
            }
            continue;
        }
        self::getRoute($path . / . $item);
    }
}

若无跳出递归的话,会遍历指定目录(n层目录)下的全部文件;加了跳出只会遍历到目标文件为止,可以提高程序运行效率

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门