此递归调用可能会陷入无限循环。我怎么跳出来?

This recursive call could get stuck in an infinit loop. How do i jump out of it?

所以我正在通过 oAuth2 访问令牌访问一些数据,我想捕获访问令牌的到期时间。当它过期时,我捕获错误代码并刷新令牌。之后我递归地调用函数。 如果由于某种原因刷新令牌不起作用,它将无限循环。 如何在尝试 1 次后跳出此循环?

function companyList($page){
//send http-request
    if($obj['errors']['status'] == '401'){
        Authentication::refreshToken();
        companyList($page);
    }
}

使用每次刷新令牌时增加 1 步的全局计数器,并添加一个 if 子句,将其与您希望的刷新限制进行比较。

示例:

$counter = 0;
function companyList($page){
    global $counter;
    //send http-request
    if($obj['errors']['status'] == '401' && $counter < 5){
        Authentication::refreshToken();
        $counter++;
        companyList($page);
    } elseif($counter >= 5){
        $counter = 0;
    }
}

希望对您有所帮助!