1

我不断收到“致命错误:在第 30 行的 /var/www/html/portal_core/build_portal.php 中的非对象上调用成员函数 prepare()”。我是 PDO 的新手,我真的用它作为测试来了解它。你们能帮我理解我做错了什么吗?

 <?php

class build_portal 
{
protected $dbh; 

function __construct($dbname,$theme)
{
    try
    {
    $dbh = new PDO('mysql:dbname='.$dbname.';host=localhost',"username","password");
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->log_error("Construct 1st Try statement 3rd Line");
    }
    catch (PDOException $e)
    {
        echo "Page Could Not Be Loaded";
        return -1;
    }



}

function log_error($cause)
{
    try
    {
    $sth = $this->dbh->prepare("SELECT * from portal_errors");
    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $sth->execute();
    }
    catch (PDOException $e)
    {
        print_r($e->errorInfo);
    }
}

} ?>

4

1 回答 1

2

这似乎是一个范围问题。你应该在构造函数中dbh赋值$this->dbh。当您稍后在 中访问它时log_error(),您期望它是一个类属性,但它最初在构造函数中被定义为局部变量。

$this->dbh = new PDO('mysql:dbname='.$dbname.';host=localhost',"username","password");
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
于 2012-10-22T02:45:33.127 回答