>im 创建一个简单的 PHP 用户系统,我有一个用户类,我使用此函数(Add)在用户类中存储新的用户值:
private function NewUser($nome, $email, $tel, $cidade, $estado, $aniversario) {
$this -> name = mysql_real_escape_string($nome);
$this -> email = mysql_real_escape_string($email);
$this -> telefone = mysql_real_escape_string($tel);
$this -> cidade = mysql_real_escape_string($cidade);
$this -> estado = mysql_real_escape_string($estado);
$this -> dia = substr($aniversario, 0, 2);
$this -> mes = substr($aniversario, 3, 2);
$this -> ano = substr($aniversario, 6);
}
public function Add($nome, $email, $tel, $cidade, $estado, $aniversario) {
$this -> NewUser($nome, $email, $tel, $cidade, $estado, $aniversario);
$Create_query = "INSERT INTO user (nome, email, telefone, cidade, estado, dia, mes, ano) VALUES ('{$this -> name}', '{$this -> email}',
'{$this -> telefone}', '{$this -> cidade}', '{$this -> estado}', '{$this - > dia}', '{$this -> mes}', '{$this -> ano}')";
$query_user = connectdb::sql_query($Create_query); // my connect class
if ($query_user) {
$answer = array('done' => 'done');
echo json_encode($answer);
}
else {
validate::returnError();
}
}
如果我尝试$this使用 -> 属性或"$this -> 属性"运行插入,我得到一个类用户的对象无法转换为字符串错误,但如果我运行那么作为"{$this -> 属性}"它有效。我已经在堆栈溢出答案中找到了这些{}方法,但没有细节,有人可以解释为什么这有效,以及它是否安全/正确?谢谢你的时间。
要回答有关大括号的问题:大括号用于显式指定变量名称的结尾。
可以在此处看到一些示例:http://docs.php.net/manual/en/language.variables.variable.php
至于错误(Object of class User
...):问题是$this -> attribute
中的空格。由于您在字符串中使用它们,因此空格被解释为它们是什么,空格。因此,它尝试仅将$this
转换为字符串,这是不可能的(请参阅错误)。如果你使用大括号,php 确切地知道变量何时开始和何时结束。
另一方面:尝试使用PDO而不是简单的mysql_query...看看这里: http://php.net/manual/de/book.pdo.php