PHP方法返回致命错误:在中不在对象上下文中时使用$this


PHP method returns Fatal error: Using $this when not in object context in

所以我有一个类:

<?php 
class Database extends PDO implements DatabaseCore
{
  private $connections;
  private $runQueryType = array('select'=>array(),
      'update'=>array(),
      'insert'=>array(),
      'delete'=>array());
  private $activeDB;
  private $databaseKeys = array();
  function __construct()
  {
    global $databases;
    foreach ($databases as $key=>$value) {
      $this->openConnection($value['dsn'], $value['user'], $value['password'], $key);
      array_push($this->databaseKeys, $key);
      $this->enumerateQueryRights($key, $value['rights']);
      Query::initQuery();
    }
  }
  function __destruct()
  {
    foreach ($this->databaseKeys as $key) {
      unset($this->connections->$key);
    }
  }
  function enumerateQueryRights($key, array $rights = array())
  {
    foreach ($rights as $r) {
      array_push($this->runQueryType[$r], $key);
    }
  }
  public function getConnection($key = 'mysqli')
  {
    //ERROR_HERE: PHP says $this is not an object at this point??
    return $this->connections->$key;
  }
  function parseConnectionInfo()
  {
  }
  function getRightByKey($key, $op = 'select')
  {
    return in_array($key, $this->runQueryType[$op]);
  }
  function closeConnection($key)
  {
    if (isset($this->connections->$key)) {
      unset($this->connections->$key);
      return TRUE;
    } else {
      return FALSE;
    }
  }
  function getConnectionInfo($key)
  {
  }
  function getConnectionKeys()
  {
    return array_values($this->databaseKeys);
  }
  function openConnection($dsn, $user, $password, $key = 'mysqli')
  {
    try {
      $this->connections->$key = new PDO($dsn, $user, $password);
      $this->connections->$key->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
      $this->connections->$key->setAttribute(PDO::ATTR_ERRMODE,     PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
      throw new Exception('Error: connection to Database');
      error_log($key  . '_CONNECT_ERROR' . "'t" . $e);
      set_message('We''ve encountered an error.  To try again, please log into <a     href="https://powerschool.bps101.net">Powerschool</a>.', 'error');
      mail('Jason.ott@bps101.net', 'Error connecting to '.$key, $e);
      die('We can''t connect to our database, an administrator has been notified');
    }
  }
  public function getError()
  {
  }
}//class

在函数getConnection($key='mysqli')中,我有return$this->connections-$key;

php抛出的错误就在这一点上:

Fatal error: Using $this when not in object context in /var/www/html/projects/fees/library/class/database.inc on line 40 (if I counted right, look for the comment in the code, ERROR_HERE)

我真的不知道为什么$this在脚本中不被视为对象。任何建议都将不胜感激,如果您需要更多信息,请咨询。

如何调用getConnection()?你想把它称为一个静态方法吗?

你在做这样的事情吗:

$conn = Database::getConnection();

如果您就是这样调用它的,那么不,您不能在该上下文中使用$this,因为它是静态的;它没有引用对象。您还需要connections属性是静态的。