php---魔术方法(__wakeup和__sleep)
来源:互联网 发布:2016淘宝有前景的类目 编辑:程序博客网 时间:2024/05/01 02:28
先写一段代码
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] => 我的秘密有回来了 )
0 0
- php---魔术方法(__wakeup和__sleep)
- php---魔术方法(__wakeup和__sleep)
- php---魔术方法(__wakeup和__sleep)
- PHP魔术方法之 __sleep() 和 __wakeup()
- PHP魔术方法 __sleep和__wakeup()
- PHP魔术方法 __sleep和__wakeup()
- php 魔术方法 __sleep() __wakeup() __toString() __debuginfo()
- 魔术方法__sleep和__wakeup的使用方法
- 魔术方法:__sleep、__wakeup使用
- php __sleep() 和__wakeup()
- 魔术方法__sleep和__wakeup、序列与反序列
- php serialize和unserialize以及__sleep() __wakeup()
- php __sleep & __wakeup
- PHP中__sleep()与__wakeup()的用法
- PHP序列化用到的构造:__sleep() __wakeup()
- PHP面向对象_对象串行化serialize(),__sleep(),__wakeup()
- php 序列化 反序列化 __sleep __wakeup
- PHP序列化用到的构造:__sleep() __wakeup()
- Qt汉字得到汉字拼音首字母
- 黑马程序员07 IO流
- 快学Scala习题解答—第十一章 操作符
- tiny_mce
- 散列技术之线性探测法
- php---魔术方法(__wakeup和__sleep)
- POJ 3304 - Segments【计算几何 - 直线线段相交判断】
- 文章标题
- 从上往下打印二叉树
- docker/compose项目笔记
- 卷积的物理意义
- C#实现磁性窗体(吸附、剥离、移动)
- Beginning Auto Layout Tutorial in iOS 7: Part 2
- UI -视图控制器UIViewController