如何将类添加到__sleep?

时间:2017-11-26 19:56:23

标签: php

我的例子:

<?php

class PDO2 {
    private $dsn, $username, $password;

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

class Connection
{
    protected $link;
    private $dsn, $username, $password;

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

    private function connect()
    {
        $this->link = new PDO2($this->dsn, $this->username, $this->password);
    }

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

$c = new Connection('aaaa', 'bbb', 'ccc');

$s = serialize($c);

print_r($s);

此回报:

  

0:10:&#34;连接&#34;:4:{S:7:&#34; *链接&#34 ;;○:4:&#34; PDO2&#34;:3:{S :9:&#34; PDO2dsn&#34 ;; S:4:&#34; AAAA&#34 ;; S:14:&#34; PDO2username&#34 ;; S:3:&#34; BBB&#34; ; S:14:&#34; PDO2password&#34 ;; S:3:&#34; CCC&#34 ;;} S:15:&#34; Connectiondsn&#34 ;; S:4:&#34; AAAA& #34 ;; S:20:&#34; Connectionusername&#34 ;; S:3:&#34; BBB&#34 ;; S:20:&#34; Connectionpassword&#34 ;; S:3:&#34 ; CCC&#34 ;;}

但是我想添加__sleep magic方法只有PDO2,用户名和dns:

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

但我注意到了:

Notice: serialize(): &quot;PDO2&quot; returned as member variable from __sleep() but does not exist in 

此:

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

运作良好。

如何将PDO2类传递给__sleep?

1 个答案:

答案 0 :(得分:0)

您的问题在__sleep所处的位置并不清楚,但我假设它在Connection。事情是我在那里看不到任何PDO2属性。

但你确实有这个。

//$this->link = new PDO2($this->dsn, $this->username, $this->password);

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

同样从设计角度来看,您无需将这些保存在属性中

private $dsn, $username, $password;

连接到数据库后,不再需要它们。