php PDO prepare()对非对象错误

时间:2012-10-22 02:43:11

标签: php mysql pdo

我不断收到“致命错误:在第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);
    }
}

} ?&GT;

1 个答案:

答案 0 :(得分: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);