先写一段代码
1
2
3
4
5
6
7
8
|
class
myClass{
public
$myContent
;
function
outMycontent(){
//dosomething
}
}
$content
=
new
myClass();
echo
serialize(
$content
);
|
输出的结果是O:7:"myClass":1:{s:9:"myContent";N;}
它竟然把一个类的给序列化了,也就是把一个类转换成了一个字符串,可以传输或者保存下来。
下面我修改一下上面的代码
1
2
3
4
5
6
7
8
|
class
myClass{
public
$myContent
;
function
__construct(
$string
){
$this
->myContent =
$string
;
}
}
$content
=
new
myClass(
'my china'
);
echo
serialize(
$content
);
|
输出的结果是O:7:"myClass":1:{s:9:"myContent";s:8:"my china";}
序列化后也对应了相应的值,但是现在有个问题,比如我这个变量是个秘密呢?而且我又得把这个类序列化传给别的地方呢?
看下面的代码
1
2
3
4
5
6
7
8
|
class
myClass{
public
$myContent
;
function
__construct(
$string
){
$this
->myContent =
$string
;
}
}
$content
=
new
myClass(
'我爱宋祖英,这是一个秘密'
);
echo
serialize(
$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
|
class
myClass{
public
$myContent
;
function
__construct(
$string
){
$this
->myContent =
$string
;
}
public
function
__sleep(){
$this
->myContent =
'这是我的秘密'
;
return
array
(
'myContent'
);
}
}
$content
=
new
myClass(
'我爱宋祖英,这是一个秘密'
);
echo
serialize(
$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
|
class
myClass{
public
$myContent
;
function
__construct(
$string
){
$this
->myContent =
$string
;
}
public
function
__sleep(){
$this
->myContent =
'这是我的秘密'
;
return
array
(
'myContent'
);
}
public
function
__wakeup(){
$this
->myContent =
'我的秘密又回来了'
;
//反序列化就不用返回数组了,就是对应的字符串的解密,字符串已经有了就不用其他的了
}
}
$content
=
new
myClass(
'我爱宋祖英,这是一个秘密'
);
print_r(unserialize(serialize(
$content
)));
|
输出的内容为:myClass Object ( [myContent] => 我的秘密有回来了 )