这是我班级的代码,当然只有相关部分:
class User {
public $id;
public function __construct($email, $password, $firstName, $lastName) {
$db = Connection::getInstance();
// check if user exists
$id = User::findUserByEmail($email);
if($id > 0){
// echo "User already exists!";
return -1;
}
// Create new row in users table
$stmt = $db->prepare("INSERT INTO `mapdb`.`user` (`email`, `password`, `firstName`, `lastName`)
VALUES (:email, :password, :firstName, :lastName);");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':firstName', $firstName, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $firstName, PDO::PARAM_STR);
$stmt->execute();
// check f user added successfully
$newID = User::findUserByEmail($email);
if($newID > 0){
echo "success, ID = ".$newID;
$this->$id = $newID;
// $this->$email = $email;
// $this->$firstName = $firstName;
// $this->$firstName = $firstName;
} else {
echo "failure";
return -1;
}
}
}
我实际上在哪里调用构造函数:
$user = new User($email, $password, $firstName, $lastName);
echo "<br>userid: ".$user->id; // (<-- this doesn't echo correctly)
无论我尝试什么,我都无法从User对象中获取值。 目前我收到以下错误: 注意:未定义的变量:id
什么可能拒绝我从变量中访问?
答案 0 :(得分:0)
问题解决了,而不是
$this->$id = $newID;
我应该
$this->id = $newID;
感谢stackoverflow:D