博客列表 >PHP对象系列化,克隆,匿名场景使用。

PHP对象系列化,克隆,匿名场景使用。

阿心
阿心原创
2020年05月06日 16:01:07606浏览

对象序列化和反序列化

  1. <?php
  2. //对象序列化:serialize — 产生一个可存储的值的表示
  3. echo serialize(123);//输出结果:i:123;i表示为整形int
  4. echo serialize('PHP');//s:3:"PHP";string字符串型和3长度
  5. echo '<hr>';
  6. class Dad
  7. {
  8. public $name='小二';
  9. protected $age=30;
  10. private $sex='man';
  11. }
  12. class Son extends Dad
  13. {
  14. private $address='地球';
  15. protected $deposit=50000;
  16. public function __get($name)
  17. {
  18. return $this->name;
  19. }
  20. protected function sx()
  21. {
  22. return __METHOD__;
  23. }
  24. // serialize() 函数会检查类中是否存在一个魔术方法 __sleep()。如果存在,该方法会先被调用,然后才执行序列化操作。__sleep() 不能返回父类的私有成员的名字。
  25. public function __sleep():array
  26. {
  27. //序列化需要返回的属性
  28. return ['name','age'];
  29. }
  30. //__wakeup反序列化先修改值/字符串
  31. public function __wakeup()
  32. {
  33. $this->name='二狗子';
  34. }
  35. }
  36. $son = new Son();
  37. //序列化对象
  38. // echo serialize($son);
  39. echo '<hr>';
  40. //结果:
  41. // O:3:"Son(被序列化的类名)":5:{s:12:"Sonaddress(类中私有属性)";s:6:"地球";s:10:"*deposit(*表示受保护属性)";i:50000;s:4:"name";s:6:"小二";s:6:"*age";i:30;s:8:"Dadsex(父类私有属性)";s:3:"man";}
  42. // file_put_contents — 将一个字符串写入文件
  43. file_put_contents('obj.txt',serialize($son));
  44. // file_get_contents — 将整个文件读入一个字符串
  45. $str=file_get_contents('obj.txt');
  46. echo $str;
  47. echo '<hr>';
  48. //反序列化unserialize
  49. $obj=unserialize($str);
  50. var_dump($obj);
  51. // object(Son)#2 (5) { ["address":"Son":private]=> string(6) "地球" ["deposit":protected]=> int(50000) ["name"]=> string(6) "小二" ["age":protected]=> int(30) ["sex":"Dad":private]=> string(3) "man" }
  52. //Son这个类一定要有,没有则失败

反序列化重写连接数据库

  1. <?php
  2. // __sleep(), __wackup()
  3. // 创建数据库连接类,
  4. // 1. 实例化的时候, 自动连接,并创建连接对象
  5. // 2. 外部对连接对象序列化时, 获取到连接参数
  6. // 3. 反序列化的时候, 自动重新连接数据库
  7. class connection
  8. {
  9. //当前连接对象
  10. protected $link;
  11. //当前连接参数
  12. private $params=[];
  13. //构造方法,完成数据库连接
  14. public function __construct($dsn,$username,$password)
  15. {
  16. $this->params['dsn']=$dsn;
  17. $this->params['username']=$username;
  18. $this->params['password']=$password;
  19. //连接过程写到connect方法里面去
  20. $this->connect();
  21. }
  22. public function connect()
  23. {
  24. //转为索引数组拿值
  25. try{
  26. $this->link=new PDO(...array_values($this->params));
  27. // $this->link = new PDO('mysql:host=127.0.0.1;dbname=Demo', 'root','123456');
  28. }catch(Exception $e){
  29. echo $e->getMessage();
  30. }
  31. }
  32. //序列化返回连接参数
  33. public function __sleep()
  34. {
  35. return['params'];
  36. }
  37. //反序列化自动连接
  38. public function __wakeup()
  39. {
  40. $this->connect();
  41. }
  42. //测试
  43. public function select($sql)
  44. {
  45. return $this->link->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  46. }
  47. }
  48. // 客户端
  49. $db=new Connection('mysql:host=localhost;dbname=Demo','root','123456');
  50. print_r($db->select('select * from user_list limit 3'));
  51. echo '<hr>';
  52. $str= serialize($db);
  53. echo $str;
  54. echo '<hr>';
  55. //反序列化后会返回新对象,重写连接查询
  56. $obj=unserialize($str);
  57. print_r($obj->select("select * from user_list limit 3"));

__clone克隆新对象

  1. <?php
  2. //__clone克隆出全新的对象
  3. class Demo
  4. {
  5. public $name='痞子';
  6. public function __clone()
  7. {
  8. $this->name='茄子';
  9. }
  10. }
  11. $demo=new Demo();
  12. $demo2= clone $demo;
  13. echo $demo2->name;

匿名类适合场景

  1. <?php
  2. // //匿名类
  3. // class Demo
  4. // {
  5. // public function Test($name)
  6. // {
  7. // return $name;
  8. // }
  9. // }
  10. // //进化论:原始
  11. // // $demo=new Demo();
  12. // // echo $demo->Test('张三');
  13. // //进化1
  14. // echo (new Demo())->Test('李四');
  15. // //进化2-->成为匿名类
  16. // echo (new class
  17. // {
  18. // public function Test1($age)
  19. // {
  20. // return $age;
  21. // }
  22. // }
  23. // )->Test1('333');
  24. //匿名类适用场景:部分接口,仅当前文件/项目使用
  25. interface iDb
  26. {
  27. public function __construct(...$params);
  28. }
  29. $res = (new class('mysql:host=localhost;dbname=Demo','root','123456') implements iDb
  30. {
  31. private $db = null;
  32. public function __construct(...$params)
  33. {
  34. $this->db = new PDO($params[0],$params[1],$params[2]);
  35. }
  36. /**
  37. * @param string $where 条件查询 例如: id = 1
  38. */
  39. public function select($where = "")
  40. {
  41. $where = empty($where) ? null : ' WHERE ' . $where;
  42. try {
  43. # 没有条件的情况下的SQL语句
  44. # SELECT * FROM user_list 这里是空' ' LIMIT 1;
  45. # 有WHERE的情况下的SQL语句 最终拼装出来的是: WHERE id=1
  46. # SELECT * FROM user_list WHERE id=1 LIMIT 1;
  47. return $this->db->query("select * from user_list {$where} limit 1")->fetchAll(PDO::FETCH_ASSOC);
  48. }catch(PDOException $e){
  49. // 输出异常信息
  50. var_dump($e->getMessage());
  51. }
  52. }
  53. }
  54. )->select();
  55. printf('<pre>%s</pre>', print_r($res,true));
  56. //匿名类场景2:函数,参数中
  57. // 正常写:
  58. // function get(object $user , string $name)
  59. // {
  60. // return $user->Test($name);
  61. // }
  62. // class User
  63. // {
  64. // public function Test($name)
  65. // {
  66. // return "我的名字是:". $name;
  67. // }
  68. // }
  69. // $user = new User;
  70. // echo get($user,'王老五');
  71. //简单写:
  72. function get(object $A , string $B)
  73. {
  74. return $A->Demo($B);
  75. }
  76. echo get(
  77. //创建匿名类
  78. new class()
  79. {
  80. public function Demo($B)
  81. {
  82. return "我告诉你我是谁,".$B;
  83. }
  84. },'二逼'
  85. );

总结:真是一个细腻的脑力活,连接数据库这里老是因为小问题都抄错,比如:需要一个空格,比如分号,逗号这里。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议