Blogger Information
Blog 26
fans 0
comment 0
visits 18438
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
__sleep()、__wakeup() 魔术方法与异常处理
雪~人胖胖
Original
879 people have browsed it

1. __sleep()与__wakeup()

  1. //__sleep():当序列化的时候自动调用
  2. //__wakeup():当反序列化的时候自动调用
  3. class Product
  4. {
  5. public $name;
  6. private $price,$sum;
  7. public function __construct($name,$price,$sum)
  8. {
  9. $this->name=$name;
  10. $this->price=$price;
  11. $this->sum=$sum;
  12. }
  13. //序列化时自动调用,return array()返回序列化的值
  14. public function __sleep()
  15. {
  16. return array('sum','price');
  17. }
  18. //反序列化时自动调用
  19. public function __wakeup()
  20. {
  21. $this->total=$this->price*$this->sum;
  22. }
  23. }
  24. $product=new Product('手机',1000,3);
  25. $res = serialize($product); //序列化
  26. $str = unserialize($res); //反序列化
  27. printf('<pre>%s</pre>',print_r($str,true));

图例


2.异常处理类

自定义异常类

  1. <?php
  2. class CustomException extends Exception
  3. {
  4. public function __toString()
  5. {
  6. return '错误提醒:'.$this->message.'<br>'.'代码异常:'.$this->code;
  7. }
  8. }
  9. class Custom
  10. {
  11. public $admin;
  12. public function __construct($admin)
  13. {
  14. $this->admin = $admin;
  15. }
  16. }
  17. try
  18. {
  19. $custom = new Custom('12345678qq.com');
  20. if(!filter_var($custom->admin,FILTER_VALIDATE_EMAIL))
  21. {
  22. throw new CustomException('邮箱格式不正确',30);
  23. }else
  24. {
  25. echo '验证成功';
  26. }
  27. }
  28. catch(CustomException $e)
  29. {
  30. echo $e;
  31. }

匿名类

  1. var_dump((new class('user1','123')
  2. {
  3. public $admin,$password;
  4. public function __construct($admin,$password)
  5. {
  6. $this->admin = $admin;
  7. $this->password = $password;
  8. }
  9. }));

总结

了解了如何自定义一个异常, __sleep和__wakeup都用在对象的序列化操作,关于匿名类没有想到什么好的例子,只能写一个最简单的了。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:匿名类现在用得并不多, 最多是用在对象参数中
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post