0
<?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()。如何修复错误?

4

1 回答 1

1

在 PHP 中,当且仅当在函数内部定义了变量 like 时,它​​才能在函数$conn中使用。“在内部定义”一词的意思是“在内部分配”。

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

   global $conn;

请注意,使用global非常糟糕的代码风格!您永远不需要使用global.

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

// 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

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

$mySessionManager 
  = new SessionManager(new CDBSession($DB_SERVER, $DB_NAME, $DB_USER,$DB_PASS));
于 2012-09-01T23:21:05.893 回答