DalekSall
DalekSall

Reputation: 385

OOP php: Method recursion returns null

I created a method for making auction names websafe, and i just added a check for dupplicate webnames, which basicly tries to fetch an auction with the given websafe name, then adds a random number to the webname. But the method ends up returning null...

private function dupplicateUrlFix($url){
    var_dump($url)//Correct
    $existingAuction = Auction::get($url, "webname");

    //if webname exists, cancatenate with random int, and check if new webname exists
    if(!empty($existingAuction->webname)){
        $newUrl = $existingAuction->webname.rand(0,9);
        $this->dupplicateUrlFix($newUrl);
        return;
    }
    var_dump($url) //Correct Not a dupplicate
    return $url;
}

public function get_url_clean($string) {
    $string = strToLower($string);
    //cleaning....
    //checks for dupplicate
    var_dump($this->dupplicateUrlFix($string)); //is null?
    die();

    return $clean;
}

I have tried switching the order in the dupplicateUrlFix() method and simply returning a string. It only goes into the if(!empty... one time.

Is there a solution for this, or a better approach?

Upvotes: 0

Views: 47

Answers (1)

u_mulder
u_mulder

Reputation: 54831

I think there's no need for recursion here:

private function dupplicateUrlFix($url) {
    $existingAuction = Auction::get($url, "webname");
    while (!empty($existingAuction->webname)) {
        $url = $existingAuction->webname . rand(0, 9);
        $existingAuction = Auction::get($url, "webname");
    }

    return $url;
}

Upvotes: 1

Related Questions