??Summary: When tracing the source code of the yii framework, I encountered the use of the __set() magic method and was a little confused, so I wrote a demo to test it, and I discovered the mystery, which is summarized as follows.
1. Let’s first take a look at how the magic method __set() is used in the book
??The purpose of using the __set() magic method is to assign values to private properties outside the object and cannot obtain the value of the private property. .
??Function prototype:
<code>void __set(string name,mixed value) </code>
Write a 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>
The above has introduced an in-depth understanding of PHP magic methods, including the content of PHP magic methods. I hope it will be helpful to friends who are interested in PHP tutorials.