??摘要:在trace yii框架源码的时候,遇到__set()魔术方法的使用,有些疑惑,所以写了demo来测试,果然发现了玄机,整理如下。
1. 先来看看书本上讲魔术方法__set()是怎么用的
??使用__set()魔术方法的目的是:在对象外部 为私有属性赋值,不能获取私有属性的值。
??函数原型:
<code>void __set(string name,mixed value) </code>
写个demo:
<code><span><span>class</span><span>CModule</span> {</span><span>private</span><span>$_components</span> = <span>''</span>; <span>public</span><span><span>function</span><span>__set</span><span>(<span>$name</span>,<span>$value</span>)</span>{</span><span>$this</span>-><span>$name</span> = <span>$value</span>; } <span>public</span><span><span>function</span><span>echoPrivate</span><span>()</span>{</span><span>echo</span><span>$this</span>->_components; } } <span>$config</span> = <span>array</span>( <span>'_components'</span>=><span>'request'</span> ); <span>$module</span> = <span>new</span> CModule(); <span>$module</span>->_components = <span>'request'</span>; <span>$module</span>->echoPrivate(); <span>//打印结果是</span><span>//request</span></code>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介绍了php 魔术方法 深度理解,包括了PHP 魔术方法方面的内容,希望对PHP教程有兴趣的朋友有所帮助。