【发布时间】:2012-12-19 18:21:32
【问题描述】:
我开发了这个使用递归调用自身的函数。我需要生成一个唯一的激活码。
它是这样的: 1. 使用单独类文件中的函数生成随机字符串。 (见第二个代码) 2. 我正在检查激活表中该字符串的唯一性,以便没有重复项。 3.万一如果重新生成随机字符串虽然我知道机会很小,但我不想冒险。所以我正在对照表记录检查它。
如果生成的激活码已经存在,则函数应该再次调用自身以生成新的激活码,整个过程继续进行,直到我们得到一个唯一的激活码,该激活码不存在于表记录中。
我的问题是,我是否正确编码了它,即递归部分。如果它不正确或者是否有人有更好或有效的方法来实现这一点,请告诉我。
注意:我从类文件中调用这些函数。简单地说,我正在使用 OOP。 所以我需要知道调用递归的代码应该是
return generateUniqueActivationCode();
或
return $this->generateUniqueActivationCode();
我们将不胜感激。
// Generate Unique Activation Code
//*********************************************************************************
public function generateUniqueActivationCode()
{
$mysql = new Mysql();
$string = new String();
// This is coming from the 2nd part of code snippet that I have added
$activation_code = $string->generateActivationCode();
// Is Activation Code Unique Check
$sql = "SELECT activation_id FROM ". TABLE_ACTIVATION_CODES ." WHERE activation_code='$activation_code' LIMIT 1";
$query = $mysql->query($sql);
if($mysql->rowCount($query) > 0)
{
// This function is calling itself recursively
return generateUniqueActivationCode();
}
else
{
return $activation_code;
}
}
这是生成随机激活码的代码
class String
{
// Generates A Random String (Can be used for generating password etc.)
//*********************************************************************************
public function generateRandomString($noofchars=8)
{
$salt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabchefghjkmnpqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= $noofchars)
{
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$string = $string . $tmp;
$i++;
}
return $string;
}
}
?>
【问题讨论】:
-
您必须始终在 PHP 中添加
$this(与 C++ 不同)。