Php recursive function return null while variable have value

我的未来我决定 提交于 2020-01-29 23:34:31

问题


This function returns NULL while $alias having value in second recursion. In first call it return the required value but when first if not matched and it recurse first the required value in avilable in $alias variable but it does not return anything.

public function checkAlias($fname='',$lname=''){

        if(!empty($fname)){
        $fname = mysql_real_escape_string($fname);
        }
        if(!empty($lname)){
        $lname = mysql_real_escape_string($lname);
        }

    $alias = strtolower($fname).strtolower($lname);
    $sql = "Select ALIAS from table where ALIAS = '$alias'";
    $query = mysql_query($sql);
    $row = mysql_fetch_row($query);
    $string_length = strlen($alias) - 1;
    $result_string = substr($alias,0,$string_length);

    if(!$row){
            print $alias;   // is printing value 
        return $alias;  // but here it returns null
    }else{
        $this->checkAlias($result_string);
        } 
    }

回答1:


You forgot to return the result of the recursion call:

return $this->checkAlias($result_string);



回答2:


You forgot the return keyword before $this->checkAlias($result_string);

Change your code to this:

public function checkAlias($fname='',$lname=''){

        if(!empty($fname)){
        $fname = mysql_real_escape_string($fname);
        }
        if(!empty($lname)){
        $lname = mysql_real_escape_string($lname);
        }

    $alias = strtolower($fname).strtolower($lname);
    $sql = "Select ALIAS from table where ALIAS = '$alias'";
    $query = mysql_query($sql);
    $row = mysql_fetch_row($query);
    $string_length = strlen($alias) - 1;
    $result_string = substr($alias,0,$string_length);

    if(!$row){
            print $alias;   // is printing value 
        return $alias;  // but here it returns null
    }else{
        return $this->checkAlias($result_string);
        } 
    }

Because the first time the code will reach the else statement, and the second time it runs it will go in the if statement. The if returns the value, but in the else you don't do anything with it, so return it and you get your value.

Stefan



来源:https://stackoverflow.com/questions/18827838/php-recursive-function-return-null-while-variable-have-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!