php---魔术方法(__wakeup和__sleep)

来源:互联网 发布:2016淘宝有前景的类目 编辑:程序博客网 时间:2024/05/01 02:28

先写一段代码

?
1
2
3
4
5
6
7
8
classmyClass{
    public$myContent;
    functionoutMycontent(){
        //dosomething
    }
}
$content= newmyClass();
echoserialize($content);

输出的结果是O:7:"myClass":1:{s:9:"myContent";N;}

它竟然把一个的给序列化了,也就是把一个转换成了一个字符串,可以传输或者保存下来。

下面我修改一下上面的代码

?
1
2
3
4
5
6
7
8
classmyClass{
    public$myContent;
    function__construct($string){
        $this->myContent = $string;
    }
}
$content= newmyClass('my china');
echoserialize($content);

输出的结果是O:7:"myClass":1:{s:9:"myContent";s:8:"my china";}

序列化后也对应了相应的值,但是现在有个问题,比如我这个变量是个秘密呢?而且我又得把这个序列化传给别的地方呢?

看下面的代码

?
1
2
3
4
5
6
7
8
classmyClass{
    public$myContent;
    function__construct($string){
        $this->myContent = $string;
    }
}
$content= newmyClass('我爱宋祖英,这是一个秘密');
echoserialize($content);

输出的结果是O:7:"myClass":1:{s:9:"myContent";s:36:"我爱宋祖英,这是一个秘密";}

我的秘密序列化后还是存在的,可是我不想我的心里话被别人看到。这个时候PHP很贴心,她知道你的问题,所以设置了魔术方法

__sleep() 就表示当你执行serialize()这个序列化函数之前时的事情,就像一个回调函数,所以在这个回调函数里面我们就可以做点事情,来隐藏我的秘密。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
classmyClass{
    public$myContent;
    function__construct($string){
        $this->myContent = $string;
    }
    publicfunction __sleep(){
        $this->myContent = '这是我的秘密';
        returnarray('myContent');
         
    }
}
$content= newmyClass('我爱宋祖英,这是一个秘密');
echoserialize($content);

输出的结果是:O:7:"myClass":1:{s:9:"myContent";s:18:"这是我的秘密";}

我的心里话被加密了,这个就是__sleep()的作用。至于__wakeup()和__sleep()大同小异,只不过是反序列化之前进行的回调函数。我不详细说了,大家看下下面的代码就明白了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classmyClass{
    public$myContent;
    function__construct($string){
        $this->myContent = $string;
    }
    publicfunction __sleep(){
        $this->myContent = '这是我的秘密';
        returnarray('myContent');
         
    }
    publicfunction __wakeup(){
        $this->myContent = '我的秘密又回来了';
        //反序列化就不用返回数组了,就是对应的字符串的解密,字符串已经有了就不用其他的了
    }
}
$content= newmyClass('我爱宋祖英,这是一个秘密');
print_r(unserialize(serialize($content)));

输出的内容为:myClass Object ( [myContent] => 我的秘密有回来了 )

0 0
原创粉丝点击