尝试从另一个类获取返回值时未定义的值'功能

时间:2015-02-13 19:37:37

标签: php pdo

当我尝试在另一个类中获取函数的返回值时,我得到Undefined Variable。 $ dbh为null

在我的入口点文件中,我实例化了一个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();
        }
    }

然后我像这样使用db对象:

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

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

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

这是在DB_Connect.php文件中实例化PDO对象并将其返回

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

错误是:

  

注意:未定义的变量:dbh in   第89行的D:\ xampp \ htdocs \ pharm_project \ DB_Functions.php

第89行是:

  

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

1 个答案:

答案 0 :(得分:1)

你的问题在这里

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