我想在类中创建一个函数,创建用户名,函数将检查用户名是否存在,然后它将增加用户名如username_1。并检查此用户名是否存在(如果存在)再次将其增加到username_2,直到创建新用户名。我创建了这个函数,但它什么都没有给我。请帮我解决我的代码中的错误。
class a{
function check_username($username){
if($usernameexist){
return true;
}
else
{
return false;
}
}
function create_username($username) {
$__name = __FUNCTION__;
if ($this->check_username($username)) {
$n++;
$username = $username . "_" . $n;
//return $__name($username); this return fatal error.
return call_user_func('create_username', $username);
} else {
return $username;
}
}
}
答案 0 :(得分:3)
不需要为此使用递归,一个简单的while(){}
循环将执行:
// your original function
function create_username($username){
// check if the username (as-is) already exists
if ($this->check_username($username)){
// use $n to keep a counter
$n = 1;
// while {username}_{n} exists, keep incrementing the counter
while ($this->check_username($username.'_'.$n)){
$n++;
/* If you don't want this to check to infinity, uncomment
* the below portion. the 100 is an arbitrary number, but use
* whatever you want as a limitation (could even make it a
* parameter in the method). Also, returning FALSE allows you to
* gracefully catch when max attempts are reached.
*
* e.g.
* if (($new_user = $obj->create_username('BradChristie')) !== FALSE){
* // user was successfully created within the max allowed attempts
* }
*/
//if ($n > 100) return FALSE
}
// return the result
return $username.'_'.$n;
}
// username was fine, return it back
return $username;
}
// recursive username check
public function create_username($username, $n = 0)
{
/* Same as above function, this is a check to prevent counting
* to infinity. uncomment to apply it
*/
//if ($n > 100) return FALSE;
// establish the username we're testing. if $n is 0,
// it's the original call to the function (don't add _0)
// if it's >0, it's part of the search so include it
$_username = $username . ($n > 0 ? '_'.$n : '');
// check if the username exists.
if ($this->check_username($_username))
{
// it exists, so make a call to this same function passing
// the original username and the value of n + 1 (move to next
// possibility)
return $this->create_username($username, $n+1);
}
// the name, as-is, was fine. return it
return $_username;
}
答案 1 :(得分:0)
在这种情况下不需要递归...一个简单的循环可以完美地完成:
function create_username($username) {
$original_username = $username;
$i=1;
while(! $this->check_username($username) ) {
$username = $original_username . '_' .$i++;
}
return $username;
}
答案 2 :(得分:0)
你的代码在几个方面都是错误的,正如其他地方所指出的那样,你想要的函数可以更好地迭代编写。
您的代码存在以下问题:
check_username
成功后,您正在进行递归检查。因此,如果您找不到原始$username
,则永远不会修改它,所以永远不要检查修改后的值。create_username
的名称,方法是附加_n
(适用于n
)。由于您在递归调用中传递了修改后的名称,因此您最终会在名称上添加多个_n
部分。