可以';t将$this作为参数传递给对象构造函数


Can't pass $this as an argument to an object constructor

我正在尝试创建一个新对象,并将创建者作为参数传递给构造函数。

    public function update_user_score(&$response){
      $user_id          = $_POST['user_id'];
      $score_details        = $_POST['score_details'];
      require_once 'Score_manager.php';
      $score_manager = new Score_manager($this);
      $score_manager->update_user_score($user_id, $score_details);
      $response['success']  = 1;
      $response['new_score']    = $new_score;
      return;
    }

在Score_manager中,构造函数是:

// constructor
function __construct($mfunc_helper) {
    require_once 'DB_Connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
    $this->$func_helper = $mfunc_helper;
}

一旦我到达行$this->$func_helper=$mfunc_helper;我得到下一个错误"Undefined variable:func_helper…";但我得到了"致命错误:引用的调用时间传递已被删除…"。我做错了什么?

$this->$func_helper应为$this->func_helper。在属性名称前面不需要额外的$。我个人认为这是非常不一致的语法,但事实就是这样

您得到的错误是因为PHP正在搜索一个名为$func_helper的局部变量。它希望使用该变量的值来查找属性名称$this。实际上,您还没有编写属性,而是读取了不存在的局部变量。因此,你会得到这个错误。

您必须使用$this->func_helper而不是$this->$func_helper来访问类属性。但您的"Fatal error: Call-time pass-by-reference has been removed"错误发生在不同的情况下。