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

时间:2013-02-07 16:14:53

标签: php class this

所以我有一个班级:

<?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')中我有     返回$ this-&gt; 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)

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

1 个答案:

答案 0 :(得分:1)

您是如何致电getConnection()的?您是否尝试将其称为静态方法?

例如你在做这样的事情:

$conn = Database::getConnection();

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