Search code examples
phprecursioninfinite-loop

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


So im accessing some data via an oAuth2 access token and i want to catch the expiration of the access token. When it expires i catch the error code and refresh the token. After that i call the function recursivly. If the refresh token for some reason does not work, it would loop infinitly. How do i jump out of this loop after 1 try?

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

Solution

  • Use a global counter that increases 1 step each time it refresh the token and add a if clause that compares it to the refresh limit you wish.

    Example:

    $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;
        }
    }
    

    Hope this helps you!