尝试从另一个 class 函数获取 return 值时未定义的值

Undefined Value when trying to get return value from another class' function

当我尝试在另一个 class 中获取函数的返回值时,我得到了未定义的变量。 $dbh 为空

在我的入口点文件中,我实例化了一个 DB_Functions 对象:

require_once ('/DB_Functions.php');
$db = new DB_Functions();

这在 DB_Function.php 文件中。

   class DB_Functions {
        private $db;
        public $dbh;

        //put your code here
        // constructor
        function __construct() {
            require_once 'DB_Connect.php';
            // connecting to database
            $this->db = new DB_Connect();
            $this->dbh = $this->db->connect();
        }
    }

然后我这样使用数据库对象:

    if ($db->isUserExisted($username)) {}....

错误在 isUserExisted(...) 函数内部。第 89 行是 $statement = $dbh....:[=​​20=]

  public function isUserExisted($username) {
        $statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");
        $statement->bindParam(':username', $username);
}

这在实例化 PDO 对象的 DB_Connect.php 文件中,returns 它

public function connect() {
        require_once('config.php');
        $dbh = new PDO('mysql:host=' . hostname . ';dbname=' . db_name, username, password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        echo 'Connected to database';
        return $dbh;
}

错误是:

Notice: Undefined variable: dbh in D:\xampp\htdocs\pharm_project\DB_Functions.php on line 89

第 89 行是:

$statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");

你的问题就在这里

public function isUserExisted($username) {
    $statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");
    $statement->bindParam(':username', $username);
}

$dbh 不存在于此函数的范围内。您需要将数据库连接作为参数传入(如 isUserExisted($dbh, $username) 中),或者将其存储在调用该函数的对象中。

例如,在对象 __construct() 中,您可能会执行 $this->dbh = $dbh 或其他操作。然后你的函数会变成

public function isUserExisted($username) {
    $statement = $this->dbh->prepare("SELECT username FROM users WHERE username = :username");
    $statement->bindParam(':username', $username);
}

More information can be found here