1

所以我有一堂课:

<?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 在脚本中当时不被视为对象。任何建议将不胜感激,如果您需要更多信息,请询问。

4

1 回答 1

1

你怎么叫getConnection()?您是否尝试将其称为静态方法?

例如,您是否正在做这样的事情:

$conn = Database::getConnection();

如果您是这样称呼它的,那么不,您不能$this在那种情况下使用它,因为它是静态的;它没有引用对象。您还需要该connections属性是静态的。

于 2013-02-07T16:37:21.467 回答