【问题标题】:PHP can't find private variables [closed]PHP找不到私有变量[关闭]
【发布时间】:2026-02-19 15:50:01
【问题描述】:

由于某种原因 PHP 找不到我的私有变量。

我收到以下错误消息

*6 FastCGI sent in stderr: "PHP message: PHP Notice: Undefined variable: _database in /var/www/simple-blog/models/database.php on line 24 PHP 消息:PHP 致命错误:未捕获的错误:无法访问 /var/www/simple-blog/models/database.php:24 中的空属性

第 24 行是我设置 $_database = $database 的那一行。

class Database {

private $_database;
private $_mysqli;


public function connect(string $host, string $username, string $password, string $database) : bool
{
    $this->$_database = $database;

    $this->$_mysqli = new mysqli($host, $username, $password, $database);

    if ($this->$_mysqli->connect_error) {
        return false;
    } else {
        return true;
    }
}
...

我尝试删除那个区域,但是 PHP 找不到变量 $_mysqli

【问题讨论】:

    标签: php class private


    【解决方案1】:

    您使用变量的方式不正确。有关 php 类变量的更多详细信息,请查看http://php.net/manual/en/language.oop5.visibility.php

    $this->$_database 更改为$this->_database。 将$this->$_mysql 更改为$this->_mysql

    【讨论】:

      【解决方案2】:

      你必须改变

      $this->$_database = $database;
      

      $this->_database = $database;
      

      $this->$_mysqli
      

      $this->_mysqli
      

      $this->$_mysqli->connect_error
      

      $this->_mysqli->connect_error
      

      【讨论】:

        【解决方案3】:

        改变声明变量的方式:

         $this->_database = $database;
        

        【讨论】: