我是 OOP 世界的新手,我一直在尽可能多地阅读它,并且从未如此困惑过。我知道它非常适合组织代码并使其更易于维护等。我已经编写了一些 OOP 代码,但我不确定它是否正确,但它可以正常工作。
我对public
private
函数以及extends
和感到困惑constructors
。我还没有在我的代码中使用它们,并且看不到在现实生活示例中我会在哪里使用它们。我读得越多并试图理解它,我就越困惑。我已经包含了我的代码,想知道是否有人可以指出错误、改进、正确使用、组织。我觉得这将有助于我更好地理解是否有经验丰富的人查看我的代码并给我指点。
class userFunctions{
const SALT_LENGTH = 9;
//Retrieves encrypted password from database returns in variable $salt
public function retrievePassword($conn,$username) {
try{
$stmt = $conn->prepare('SELECT `password` FROM `users` WHERE `userName`= :userName');
$stmt->bindValue(':userName', $username);
$stmt->execute();
$salt = $stmt->fetchColumn();
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
return $salt;
}
//End of retrieve password method
////////////////////////////////////////////////////////////////
//Generate an encrypted password method
public function generateHash($password, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, self::SALT_LENGTH);
} else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($salt . $password);
}
//End of generate encrypted password method
////////////////////////////////////////////////////////////////
//Check database for duplicate username
public function userCheck($conn,$userName){
try{
$stmt = $conn->prepare('SELECT COUNT(*) FROM `users` WHERE `userName` LIKE CONCAT("%",:userName)');
$stmt->bindValue(':userName', $userName);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
//End of Check databade for duplicate username
////////////////////////////////////////////////////////////////
//Add user to database
public function Register($conn,$userName,$encryptedPass){
try{
$stmt = $conn->prepare('INSERT INTO users (userName, password) VALUES (:userName, :password)');
$stmt->execute(array(':userName' => strip_tags($userName), ':password' => $encryptedPass));
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
//End of add user to database
////////////////////////////////////////////////////////////////