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

先写一段代码

?
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值