代码之家  ›  专栏  ›  技术社区  ›  Imnotapotato

将对象保存到会话-如何像以前一样从会话获取对象?

  •  -1
  • Imnotapotato  · 技术社区  · 7 年前

    当从会话中取回它时,如何使它的所有方法都工作?(如有可能,与原件完全相同)

    <?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);

    1 回复  |  直到 7 年前
        1
  •  1
  •   BadPiggie    7 年前

    你应该使用这个函数 serialize() unserialize() PHP SESSION .

    代码应该是,

    session_start();
    
    $a = your_object;
    $b = serialize($a);
    
    $_SESSION["serialized_data"] = $b; 
    # To store in Session
    
    $unserialized_data = unserialize($_SESSION["serialized_data"]); 
    # To get from Session as Object
    
    推荐文章