在php类和函数中调用非对象的成员函数prepare()

时间:2012-09-01 23:11:42

标签: php pdo

<?php
    try{
     $conn = new PDO("mysql:host=$DB_SERVER;dbname=$DB_NAME",$DB_USER,$DB_PASS);
    }

class SessionManager {

        var $life_time;
        function SessionManager() {
            global $conn;
            $this->life_time = get_cfg_var("session.gc_maxlifetime");

            // Register this object as the session handler
            session_set_save_handler( 
                array( &$this, "open" ), 
                array( &$this, "close" ),
                array( &$this, "read" ),
                array( &$this, "write" ),
                array( &$this, "destroy"),
                array( &$this, "gc" )
            );
        }



        function read( $id ) {
            global $conn;
            $data = "";
            $time = time();
            $newid = $id;       
            $sql = "SELECT session_data FROM session_tmp WHERE session_id=? AND expired_date > ?";
            $q = $conn->prepare($sql);
            $result = $q->execute(array($newid, $time));
            while($r = $q->fetch(PDO::FETCH_ASSOC)){
                $data = $row['session_data'];
            }
            return $data;
        }


        function write( $id, $data ) {            
            $time = time() + $this->life_time;
            global $conn;
            $newid = $id;
            $newdata = $data;
            $sql = "SELECT session_id FROM session_tmp WHERE session_id = ?"; // error happen here!!!!
            $q = $conn->prepare($sql);
            $result = $q->execute(array($newid));
            return TRUE;
        }
}

我将global $conn;添加到function read()并修复错误。我不知道为什么global $conn;无法解决function write()上的错误。如何解决错误?

1 个答案:

答案 0 :(得分:1)

在PHP中,当函数时,函数<{1}}中有一个变量可用,当且仅当它在函数中定义时才可用。 “内部定义”一词意味着“在内部分配”。

在您的情况下,$conn函数中未定义$conn,但在所有函数之外 。因此,您需要告诉write()它应该引用全局变量$ conn。这是使用

完成的
write()

注意, global $conn; 的使用是严重错误的代码风格!您永远不需要使用global

而不是全局,你可能会这样做:

global

最后,你必须像这样使用SessionManager:

// This class should actually be a singleton class
// http://en.wikipedia.org/wiki/Singleton_pattern
//
class CDBSession {

  protected 
    $conn;

  public function __construct( $DB_SERVER, $DB_NAME, $DB_USER,$DB_PASS ) {

      $this->conn 
         = new PDO("mysql:host=$DB_SERVER;dbname=$DB_NAME",$DB_USER,$DB_PASS);

  } // __construct

  public function getPDO() {

      return $this->conn;

  }      

}

class SessionManager {

  protected 
    $_PDOSession;

  public function __construct( CDBSession $theDBSession ) {

      $this->_PDOSession = $theDBSession;

  } // __construct


  ... other methods need to access $this->_PDOSession->getPDO() too ...

} // class SessionManager