【问题标题】:PHP Class issue Using $this when not in object context [duplicate]PHP类问题不在对象上下文中使用$this [重复]
【发布时间】:2014-11-11 15:31:31
【问题描述】:

这是我的课,一个简单的 pdo 包装器。当我从我的主页调用查询函数时,它会抛出这个错误:

不在对象上下文中使用 $this

当我尝试从 __construct 调用查询时,它工作正常。

有人可以帮忙吗?

$db = new Database();
$db->query("some sql");


class Database
{
    public $connectionString;
    public $_PDOInstance = "";

    public function __construct($errorCallbackFunction = "",$errorFormat = "")
    {
        global $vars;

        if(!$this->_PDOInstance)
        {
            if(empty($errorCallbackFunction))
            {
                $errorCallbackFunction = "print_r";
            }

            if(empty($errorFormat))
            {
                $errorFormat = "html";
            }

            if(strtolower($errorFormat) !== "html")
            {
                $errorFormat = "text";
            }

            $this->_errorMsgFormat = strtolower($errorFormat);
            $this->_errorCallbackFunction = $errorCallbackFunction;

            $dsn = "mysql:host=".$vars['dbi']['host'].";dbname=".$vars['dbi']['name'].";";
            $this->connectionString = $dsn;
            $driver_options =   array(
                                    PDO::ATTR_PERSISTENT => false,
                                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                                );
            try
            {
                $this->_PDOInstance = new PDO($dsn, $vars['dbi']['user'], $vars['dbi']['pass'], $driver_options);
                $this->_PDOInstance->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('dbStatement'));
                $this->_PDOInstance->query('SET NAMES utf8');       
            } 
            catch(PDOException $e)
            { 
                $msg = $e->getMessage();
                exit("PDO CONNECTION ERROR: ".$msg. "<br/>");
            }
        }
        return $this->_PDOInstance;
    }

    public static function query($statement)
    {           
        try
        {
            $stuff = $this->_PDOInstance->query($statement);
        }
        catch(PDOException $e)
        {
            $msg = $e->getMessage();

            if(ENV !== 'live')
            {
                print_r("Error : ".$msg."<br>"."SQL : ".$statement);
            }
            throw new PDOException($msg);
        }
        return $stuff;
    }
}

【问题讨论】:

  • 确切的错误是什么?更具体一点
  • 我们需要看看您在“主页”上是如何称呼它的
  • 另外,题外话,为什么我的代码不起作用。

标签: php class pdo


【解决方案1】:

您不能同时使用static function query$this,因为您没有在$this 中表示的类对象。还是可以用self::

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多