当从会话中取回它时,如何使它的所有方法都工作?(如有可能,与原件完全相同)
<?php
namespace MyApp\Models;
use MyApp\Core\Database;
use MyApp\Helpers\Session;
use MyApp\Core\Config;
class Customer {
private $db;
public $host;
public $dbName;
public $type;
public function __construct($customerName = NULL)
{
# Get database instance
$this->db = Database::getInstance();
# If customer name passed as a variable
if ( $customerName ) {
# Get Customer data from db
$data = $this->customerDataByName($customerName);
if ($data) {
# Set data to $this Obj
$this->setCustomerData($data['db_host'], $data['db_name'], $data['system_type']);
# Set $this Obj to Session
$this->setCustomerToSession();
} else {
return false;
}
}
}
public function setCustomerData($host, $dbName, $type)
{
# Set customer host in object
$this->host = $host;
# Set customer name in object
$this->dbName = $dbName;
# Set customer type in object
$this->type = $type;
}
public function setCustomerToSession()
{
Session::put(Config::$customer, $this);
}
public function customerDataByName($customer_name)
{
return $this->db->row("SELECT `db_name`, `db_host`, `system_type` FROM customers WHERE customer_name = :customer_name", array('customer_name' => $customer_name));
}
public function __sleep()
{
return array('host', 'dbName', 'type', 'customerDataByName()', 'setCustomerData()' );
}
public function __wakeup()
{
$this->db = Database::getInstance();
}
}
使用
__sleep()
方法,我尝试以几种不同的方式添加函数,但没有成功。。我希望它也能连接到数据库。
并尝试使用其他方法:
public function setCustomerToSession()
{
$serialized = serialize($this);
Session::put(Config::$customer, $serialized);
}
__wakup
和
__sleep
,然后尝试:
$a = unserialize($_SESSION['customer']);
var_dump($a);
PHP致命错误:未捕获PDO异常:无法序列化或
在中取消序列化PDO实例。。。
指向
$serialized = serialize($this);