当前位置:Gxlcms > PHP教程 > php的拦截器实例代码分析

php的拦截器实例代码分析

时间:2021-07-01 10:21:17 帮助过:17人阅读

PHP中提供了内置的拦截器,可以拦截对未定义的方法和属性的调用。这篇文章主要介绍了PHP的拦截器,以实例形式分析了常见的各类拦截器的用法,非常具有实用价值,需要的朋友可以参考下,具体如下:

PHP提供了几个拦截器,用于在访问未定义的方法和属性时被调用,如下所示:

1、__get($property)
功能:访问未定义的属性是被调用

2、__set($property, $value)
功能:给未定义的属性设置值时被调用

3、__isset($property)
功能:对未定义的属性调用isset()时被调用

4、__unset($property)
功能:对未定义的属性调用unset()时被调用

5、__call($method, $arg_array)
功能:调用未定义的方法时被调用

下面将通过一个小程序来说明这些拦截器的用途:

  1. class intercept_demo{
  2. private $xingming = "";
  3. private $age = 10;
  4. // 若访问一个未定义的属性,则将调用get{$property}对应的方法
  5. function __get($property){
  6. $method = "get{$property}";
  7. if (method_exists($this, $method)){
  8. return $this->$method();
  9. }
  10. }
  11. // 若给一个未定义的属性设置值,则将调用set{$property}对应的方法
  12. function __set($property, $value){
  13. $method = "set{$property}";
  14. if (method_exists($this, $method)){
  15. return $this->$method($value);
  16. }
  17. }
  18. // 若用户对未定义的属性调用isset方法,
  19. function __isset($property){
  20. $method = "isset{$property}";
  21. if (method_exists($this, $method)){
  22. return $this->$method();
  23. }
  24. }
  25. // 若用户对未定义的属性调用unset方法,
  26. // 则认为调用对应的unset{$property}方法
  27. function __unset($property){
  28. $method = "unset{$property}";
  29. if (method_exists($this, $method)){
  30. return $this->$method();
  31. }
  32. }
  33. function __call($method, $arg_array){
  34. if (substr($method,0,3)=="get"){
  35. $property = substr($method,3);
  36. $property = strtolower(substr($property,0,1)).substr($property,1);
  37. return $this->$property;
  38. }
  39. }
  40. function testIsset(){
  41. return isset($this->Name);
  42. }
  43. function getName(){
  44. return $this->xingming;
  45. }
  46. function setName($value){
  47. $this->xingming = $value;
  48. }
  49. function issetName(){
  50. return !is_null($this->xingming);
  51. }
  52. function unsetName(){
  53. $this->xingming = NULL;
  54. }
  55. }
  56. $intercept = new intercept_demo();
  57. echo "设置属性Name为Li";
  58. $intercept->Name = "Li";
  59. echo "\$intercept->Name={$intercept->Name}";
  60. echo "isset(Name)={$intercept->testIsset()}";
  61. echo "";
  62. echo "清空属性Name值";
  63. unset($intercept->Name);
  64. echo "\$intercept->Name={$intercept->Name}";
  65. echo "";
  66. echo "调用未定义的getAge函数";
  67. echo "age={$intercept->getAge()}";

以上就是php 的拦截器实例代码分析的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行