0

我正在尝试使用一些记住我的课程,现在问题是我得到了

Call to a member function prepare() on a non-object

而且我没有收到任何错误:

索引.php:

    try {
    $connection = new PDO('mysql:host=localhost;dbname=ibids', 'root', '');
    } 

catch (PDOException $e)
    {
        printf ($e);
    }

$storage = new Rememberme_Storage_PDO($connection);
$rememberMe = new Rememberme($storage);

我将连接发送到此文件: pdo.php 并在那里使用此代码:

class Rememberme_Storage_PDO extends Rememberme_Storage_DB {

  /**
   *
   * @var PDO
   */
  protected $connection;
  public function getConnection() {
    return $this->connection;
  }

  public function setConnection(PDO $connection) {

   try  {
     $this->connection = $connection;
        } 
    catch (PDOException $e)
        {
            printf ($e);
        }
  }
}

我在这个函数上有错误:

** Rememberme_Storage_PDO 类中的这个函数

   public function storeTriplet($credential, $token, $persistentToken, $expire=0) {
    $sql = "INSERT INTO {$this->tableName}({$this->credentialColumn}, " .
           "{$this->tokenColumn}, {$this->persistentTokenColumn}, " .
           "{$this->expiresColumn}) VALUES(?, SHA1(?), SHA1(?), ?)";
    $query = $this->connection->prepare($sql);

    if(!$query->execute(array($credential, $token, $persistentToken, date("Y-m-d H:i:s", $expire))))
        {
        die('excute faild');
        }
  }

说:

 Fatal error: Call to a member function prepare() on a non-object in F:\wamp\www\rememberme-master\src\Rememberme\Storage\PDO.php on line 44

我是 PDO 的新手,我做错了什么?

4

2 回答 2

2

看起来没有构造函数。如果您在使用时传递变量,new则将其传递给构造函数而不是setter. 所以当使用这个时:

$storage = new Rememberme_Storage_PDO($connection);

......你需要Rememberme_Storage_PDO

public function __construct(\PDO $connection) {
    $this->setConnection($connection);
}
于 2013-09-25T10:24:49.443 回答
0

显然 $this->connection 不是一个对象 .. 这很明显,因为您没有使用 setConnection 公共函数..

我只看到您试图将连接对象传递给构造函数,但没有构造函数将其实际存储在$this->connection属性中。

也许

$storage = new Rememberme_Storage_PDO($connection);

应该:

$storage = new Rememberme_Storage_PDO();
$storage->setConnection($connection);
于 2013-09-25T10:25:28.540 回答