【问题标题】:Undefined Variable in PHP, after clearly defining itPHP中的未定义变量,明确定义后
【发布时间】:2026-02-21 23:35:01
【问题描述】:

我收到此错误。 未定义变量:第 15 行 C:\xampp\htdocs\Wishlist\BookDao.php 中的 db_conn

<?php
require_once ('Book.php');
require_once ('DBConn.php');

class BookDao {
 private $db_conn;

function __construct() {
    $db_conn=new DBConn();
}

public function addBook(Book & $book) {
    //if (isbnAvailable($book -> getIsbn())) {
        $db_conn->connect();
        $db_conn -> setQuery("Insert into books(ISBN, Title, Author)
            Values('$book->getIsbn()','$book->getTitle()','$book->getAuthor()')");
        $db_conn -> executeQuery();
        $db_conn -> close();
        if (mysqli_num_rows($db_conn -> getResult())) {
            $db_conn -> freeResult();
            return true;
        } else {
            $db_conn -> freeResult();
            return false;
        }

}

public function isbnAvailable($isbn) {
    $db_conn -> connect();
    $db_conn -> setQuery("Select isbn from books where ISBN = ' . $isbn . '");
    $db_conn -> executeQuery();
    $db_conn -> close();
    if (mysqli_num_rows($db_conn -> getResult())) {
        $db_conn -> freeResult();
        return false;
    } else {
        $db_conn -> freeResult();
        return true;
    }
}

}
?>

这似乎是一个范围问题,但我不确定,我也是 PHP 新手,所以这很可能是一些愚蠢的错误。

【问题讨论】:

    标签: php variables scope undefined


    【解决方案1】:

    您处于班级环境中。要设置和访问您的私有类变量$db_conn,您需要在任何地方使用$this-&gt;db_conn

    在你的构造函数中:

    function __construct() {
        $this->db_conn=new DBConn();
    }
    

    在所有其他方法中:

    public function addBook(Book & $book) {
        $this->db_conn->connect();
        ...
    
    public function isbnAvailable($isbn) {
        $this->db_conn->connect();
        ...
    

    更多关于 PHP 类和属性:

    http://www.php.net/manual/en/language.oop5.basic.php http://www.php.net/manual/en/language.oop5.properties.php

    【讨论】:

    • @KarmicDice 哈!我知道这只是一场打字比赛。 =)
    【解决方案2】:

    PHP 中的成员需要通过$this 访问。所以只需将$db_conn 更改为$this-&gt;db_conn 即可。

    【讨论】:

      【解决方案3】:

      使用$this-&gt;db_conn

      php 类需要 $this 在所有类作用域变量之前。

      【讨论】:

        【解决方案4】:

        在定义它之后,你需要在任何地方使用这个变量作为$this-&gt;db_conn :)

        【讨论】:

          【解决方案5】:

          $db_conn 不是全局变量,它作为类变量存在,因此您必须这样引用它。

          $db_conn 的所有实例都应该是 $this->db_conn

          【讨论】: