这是我使用php5的第一个代码,我需要你的帮助来优化我的班级用户,我想知道:
real_escape_string
?$var
和$_var
之间的区别是什么(因为我使用了两者,但我不知道有什么区别)?我现在的代码是:
class user {
private $_id;
private $_name;
private $_mail;
private $_login;
private $_pass;
private $_conn;
public
function __construct($conn) {
$this - > conn = $conn;
}
// function : add user
public
function addUser($name, $mail, $login, $pass) {
$conn = $this - > conn;
$this - > name = $conn - > quote($name);
$this - > login = $conn - > quote($login);
$this - > mail = $conn - > quote($mail);
$this - > pass = password_hash($pass, PASSWORD_DEFAULT);
$sql = "INSERT INTO user(name, mail, login, pass) VALUES(?,?,?,?)";
$st = $conn - > prepare($sql);
$st - > execute([
$this - > name,
$this - > mail,
$this - > login,
$this - > pass,
]);
}
// Get User
public
function login($login, $pass) {
$conn = $this - > conn;
$login = $conn - > quote($login);
$pass = password_hash($pass, PASSWORD_DEFAULT);
$sql = "SELECT * FROM user WHERE login=? AND pass=?";
$st = $conn - > prepare($sql);
$st - > execute([
$login,
$pass,
]);
}
//function : delete user
public
function deleteUser() {
$conn = $this - > conn;
$sql = "DELETE FROM user WHERE id=".$this - > id;
$conn - > exec($sql);
}
// Getters and Setters
public
function __get($property) {
if (property_exists($this, $property)) {
return $this - > $property;
}
}
public
function __set($property, $value) {
if (property_exists($this, $property)) {
$this - > $property = $value;
$conn = $this - > conn;
$value = $conn - > quote($value);
$sql = "UPDATE user SET ".$property.
"=? WHERE id=?";
$st = $conn - > prepare($sql);
$st - > execute([
$value,
$this - > id,
]);
}
return $this;
}
}
答案 0 :(得分:0)
您不必将real_escape_string()
与预准备语句一起使用,因为它们会根据需要自动转义。
就$var
与$_var
:
它基本上只是一个不同的命名约定。在文件的顶部,您可以定义一些私有变量:
private $_id;
private $_name;
private $_mail;
private $_login;
private $_pass;
private $_conn;
这些使用$_var
。这是为了帮助您将它们与代码中的公共变量$var
分开。这有意义吗?