【问题标题】:OOP php: Method recursion returns nullOOP php:方法递归返回null
【发布时间】:2014-11-13 03:34:51
【问题描述】:

我创建了一种使拍卖名称成为网络安全的方法,并且我只是添加了一个重复网络名称检查,它基本上尝试使用给定的网络安全名称获取拍卖,然后向网络名称添加一个随机数。但该方法最终返回 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;
}

我尝试在 dupplicateUrlFix() 方法中切换顺序并简单地返回一个字符串。它只进入 if(!empty... 一次。

是否有解决方案或更好的方法?

【问题讨论】:

  • 我认为$existingAuction->webname.rand(0,9) 无效。也许做$newUrl = ($existingAuction->webname).rand(0,9)
  • @Doctus 间隔为$newUrl = $existingAuction->webname . rand(0,9) 更具有视觉感。
  • @MichaelBerkowski 这是主观的 - 它们都是有效的
  • @Doctus 我没有说你是无效的。我以为您暗示它是无效的,因为该点旨在用作类运算符。我误读了你的评论。
  • 哦,我明白你的意思了!是的,我不太确定,但我知道过去在将对象属性与字符串连接时,我必须将它们括在括号中。

标签: php oop recursion


【解决方案1】:

我认为这里不需要递归:

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

【讨论】:

  • 行得通!谢谢!它甚至看起来更干净:)
  • 甚至可以转换成do .. while,以免$existingAuction = ...写两次)
  • 当你点击第 12 个名字时,你会有一个无限循环。假设 get() 方法访问数据库,您将有一个无限循环访问数据库。
  • 我们仍然可以向while 添加一些计数器,例如超过尝试次数时抛出异常。
  • rand(0, 9) 返回一个字符。因此,您将获得基本名称 foo 加上 10 个额外名称 foo0、foo1 等。经过 11 次尝试后,您将没有更多名称可供尝试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2014-01-24
  • 1970-01-01
相关资源
最近更新 更多