详解php魔术方法函数__get()和__set() - php语言 -

详解php魔术方法函数__get()和__set()

时间:2012-09-27 09:16:29   来源:   评论:加载中...   点击:加载中...
详解php魔术方法函数__get()和__set()。 先看看php官方文档的解释: __set() isun when writing data to inaccessible properties. _...

详解php魔术方法函数__get()和__set()。

先看看php官方文档的解释:

__set() isun when writing data to inaccessible properties.
__get() is utilized foreading data from inaccessible properties.

究竟用中文怎么翻译呢?

inaccessible :n. 难达到;难接近;无法理解。

有代码有真相:
代码如下:
 
a); //output: 123 var_dump($s->b); //output: 123 var_dump($s->c); //output: null var_dump($s->d); //output: 0 var_dump($s->e); //output: 123 $s->a = 3; //output: This is set function $s->c = 3; //no output $s->f = 3; //output: This is set function ?> 


结果分析:
如果没有__get方法,执行 var_dump($s->a) var_dump($s->b) 会有致命的错误
如果没有__get方法,执行 var_dump($s->e) 会有一个notice,提示没有定义属性 $e

总结:
1. 从一个难以访问的属性读取数据的时候 __get() 方法被调用
2. 向一个难以访问的属性赋值的时候 __set() 方法被调用
3. 难以访问包括:(1)私有属性,(2)没有初始化的属性
4. __isset() __unset() 也类似


相关热词搜索:

 
上一篇:PHP用XML-RPC构造Web Service
下一篇:PHP程序内存大小获取(memory_get_usage)
收藏 将此文推荐给朋友
分享到: