: This article mainly introduces the method of private attributes of the class external handler class in php. if you are interested in the PHP Tutorial, please refer to it.
We all know that private attributes of a class are not accessible outside the class, including sub-classes. For example, the following code:
_ Prop ;}; $ a = new Example1 (); var_dump ($ r ($ a); // running result: Fatal error: Cannot access property private Example1 :: $ _ prop?>
However, in some cases, we need the private attributes of the category class. the following methods can be implemented:
1. use reflection
_ Prop ;}; $ a = new Example1 (); $ rfp = new ReflectionProperty ('example1', '_ prop'); $ rfp-> setAccessible (true ); var_dump ($ rfp-> getValue ($ a); // result output: string 'test' (length = 4)?>
2. use Closure: bind ()
This method is added in php 5.4.0.
_ Prop ;}; $ a = new Example1 (); $ r = Closure: bind ($ r, null, $ a); var_dump ($ r ($ )); // result output: string 'test' (length = 4)?>
In addition, we can also use the reference method for access, so that we can modify the private attributes of the class:
_ Prop;}, null, $ a); $ cake = & $ r ($ a); $ cake = 'Lie '; var_dump ($ r ($ )); // result output: string 'Lil' (length = 3)
Therefore, we can encapsulate a function to read/set the private attributes of the class:
$property; }, $object, $object)->__invoke(); return $value; }; ?>
Closure: bind () also has a very useful feature. we can use this feature to dynamically add methods to a class. The official document provides an example:
Methods [$ methodName] = Closure: bind ($ methodCallable, $ this, get_class ();} public function _ call ($ methodName, array $ args) {if (isset ($ this-> methods [$ methodName]) {return call_user_func_array ($ this-> methods [$ methodName], $ args );} throw RunTimeException ('There is no method with the given name to call');} class HackThursday {use hour Rait; private $ dayOfWeek = 'Thursday';} $ test = new Hac KThursday (); $ test-> addMethod ("addedMethod", function () {return 'method I am added dynamically ';}); echo $ test-> addedMethod (); // result output: is the method dynamically added?>
The above describes the php method for private attributes of the class external variables class, including some content, and hope to be helpful to friends who are interested in the PHP Tutorial.