PHP魔术方法

* 魔术方法 : 
*
* __construct : -> 当类实例化的时候被调用
* __destruct : -> 在类实例对象被销毁的时候调用
* __call : -> 在调用的方法不存在的时候 或者 权限不够的时候调用
* __callStatic: -> 在调用的静态方法不存在的时候 或者 权限不够的时候调用
* __get : -> 在类中的属性为私有的时候 想要在外部获取值 则需要重写__get即可
* __set : -> 在类中的属性为私有的时候 想要在外部写入值 则需要重写__set即可
* __isset : -> 重写isset()函数 在外部调用查看某类中是否有该私有属性定义的时候调用
* __unset : -> 当在类外部使用unset()函数来删除私有成员时自动调用的
* __sleep : -> 对象在被序列化的时候调用(serialize)
* __wakeup : -> 对象被反序列化的时候调用(unserialize)
* __toString : -> 当被打印出无效数据的时候调用 echo 如果要打印对象 就会被调用
* __invoke : -> 当对象以函数的方式调用的时候 invoke 就会被调用
* __set_state : -> var_export()的使用时调用
* __clone : -> 使用clone关键字的时候调用
* __debugInfo : -> var_dump()一个类时的回应

ps: 最后3个没有写示例 ... 自行脑补

 1 class Answer{
 2     private $answer;
 3     public  $kins = 1;
 4 
 5     public function __construct()
 6     {
 7         echo '当类实例化的时候被调用<br>';
 8     }
 9 
10     public function __destruct()
11     {
12         // TODO: Implement __destruct() method.
13         echo '在类实例对象被销毁的时候调用<br>';
14     }
15 
16     public function __call($name, $arguments)
17     {
18         // TODO: Implement __call() method.
19         echo '在调用的方法不存在的时候 或者 权限不够的时候调用<br>';
20     }
21 
22     public static function __callStatic($name, $arguments)
23     {
24         // TODO: Implement __callStatic() method.
25         echo '在调用的静态方法不存在的时候 或者 权限不够的时候调用<br>';
26     }
27 
28     public function __set($name, $value)
29     {
30         echo '当给私有属性answer赋值的时候调用<br>';
31         $this->$name = $value;
32     }
33 
34     public function __get($name = '')
35     {
36         echo '当获取私有属性answer的时候调用<br>';
37         return $this->$name;
38     }
39 
40     public function __isset($name = '')
41     {
42         echo '判断是否定义了answer<br>';
43         return isset($this->$name);
44     }
45 
46     public function __toString()
47     {
48         // TODO: Implement __toString() method.
49         return '当被打印出无效数据的时候调用<br>';
50     }
51 
52     public function __invoke($value = '')
53     {
54         // TODO: Implement __invoke() method.
55         echo '当对象以函数的方式调用的时候  invoke 就会被调用<br>';
56         $this->kins = $value;
57     }
58 
59     private function getName()
60     {
61         return 'kinsFeng';
62     }
63 
64     private static function getSex()
65     {
66         return 'man';
67     }
68 
69 }
70 
71 $a = new Answer();
72 
73 echo $a::getSex();
74 unset($a);
75 $a('a');
76 echo $a->kins;
77 var_dump($a);
78 echo $a->kins;
79 $a->answer = 'a';
80 $b = $a->answer;
81 isset($a->answer);exit;
原文地址:https://www.cnblogs.com/kinsFeng/p/9199073.html