【问题标题】:Object Variable Remains Undefined after being Set in Constructor对象变量在构造函数中设置后保持未定义
【发布时间】:2017-05-28 01:36:19
【问题描述】:

这是我班级的代码,当然只有相关部分:

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

什么可能会拒绝我访问该变量?

【问题讨论】:

标签: php oop


【解决方案1】:

问题解决了,而不是

$this->$id = $newID;

我应该有

$this->id = $newID;

感谢stackoverflow :D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2013-10-16
    • 2023-03-21
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多