对象变量在构造函数中设置后仍然未定义 [英] Object Variable Remains Undefined after being Set in Constructor

查看:42
本文介绍了对象变量在构造函数中设置后仍然未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is the code of my class, only relevant parts of course:

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;
      }
   }
}

我实际调用构造函数的地方:

And where I actually call the constructor:

$user = new User($email, $password, $firstName, $lastName);
echo "<br>userid: ".$user->id; // (<-- this doesn't echo correctly)

无论我怎么尝试,我都无法从 User 对象中获取值.目前我收到以下错误:注意:未定义变量:id

I cannot get the value from the User object whatever I try. At the moment I get the following error: Notice: Undefined variable: id

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

What could possibly deny me access from the variable?

推荐答案

问题解决了,而不是

$this->$id = $newID;

我应该有

$this->id = $newID;

谢天谢地有 stackoverflow :D

Thank goodness for stackoverflow :D

这篇关于对象变量在构造函数中设置后仍然未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆