2012-06-18 85 views
0

我的网上商店有以下这些类。反序列化pdo mysql错误 - 无效的数据源名称

这个超类包含子类使用的所有常用方法。

class grandpa 
{ 
    public function test1($string) 
    { 
     return $string; 
    } 
} 

所以做的PDO连接,

class database_pdo extends grandpa 
{ 
    protected $connection = null; 
    protected $dsn,$username,$password; 

    public function __construct($dsn,$username,$password) 
    { 
     $this->dsn = $dsn; 
     $this->username = $username; 
     $this->password = $password; 
     $this->get_connection(); 
    } 

    public function get_connection() 
    { 
     try 
     { 
      $this->connection = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); 
      $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
     catch (PDOException $e) 
     { 
      $this->get_error($e); 
     } 
    } 

    public function __sleep() 
    { 
     return array('dsn', 'username', 'password'); 
    } 


    public function __wakeup() 
    { 
     $this->get_connection(); 
    } 

    public function get_error($e) 
    { 
     $this->connection = null; 
     die($e->getMessage()); 
    } 

    public function __destruct() 
    { 
     $this->connection = null; 
    } 
} 

我有这个类从PDO为需要PDO连接等常见方法来扩展,

class papa extends database_pdo 
{ 
    protected $connection = null; 

    public function __construct($connection) 
    { 
     $this->connection = $connection; 

    } 

    public function test2($string) 
    { 
     return $string; 
    } 

} 

的子类,

class kido_1 extends papa 
{ 

    public function __construct($connection) 
    { 
     parent::__construct($connection); 
    } 

    public function test3($string) 
    { 
     return $string; 
    } 
} 

How它使用的类以上,

# Host used to access DB. 
define('DB_HOST', 'localhost'); 

# Username used to access DB. 
define('DB_USER', 'xxx'); 

# Password for the username. 
define('DB_PASS', 'xxx'); 

# Name of your databse. 
define('DB_NAME', 'xxx'); 

# Data source name. 
define('DSN', 'mysql:host='.DB_HOST.';dbname='.DB_NAME); 

$connection = new database_pdo(DSN,DB_USER,DB_PASS); 

$kido = new kido($connection); 

$_SESSION['cart'] = serialize($kido); 

$kido = unserialize($_SESSION['cart']); 

print_r($kido->test3('hello')); 

我得到这个错误,

无效的数据源名称

它由unserialize(),我需要为我的车的数据引起...

我该如何解决这个问题?或者重写这些类的更好方法?

回答

1

您的papa::connection是一个PDO对象。因此,当您尝试序列化$kido时,您试图序列化资源which is not possible。 尝试在database_pdo::__sleep()方法中添加$this->connection = null;

+0

对不起,我不是很明白 - '__sleep()'方法是在类database_pdo'的'而不是'grandpa' - 你的意思' papa'? – laukok

+0

@lauthiamkok是的,抱歉的困惑(编辑) – RandomSeed

+0

也删除了“[PDO对象]初始化在建设时间”,我确实混淆了'爷爷'和'爸爸' – RandomSeed

0

一个解决方案,我认为......

class papa extends grandpa 
{ 
    protected $connection = null; 

    public function __construct($connection) 
    { 
     $this->connection = $connection; 

    } 

    public function test2($string) 
    { 
     return $string; 
    } 

} 
+1

啊哈!这一切现在变得清晰;) – RandomSeed

+0

哈哈谢谢ypu :-) – laukok