As we all know, the private properties of a class are inaccessible outside of the class, including subclasses, which are not accessible. For example, the following code:
class Example1{ private $_prop = 'test'; } $r = function(Example1 $e){ return $e->_prop; }; $a = new Example1(); var_dump($r($a)); //运行结果:Fatal error: Cannot access private property Example1::$_prop ?>
But in some cases we need to access the private properties of the class, there are several ways to do it:
1. Using Reflection
class Example1{ private $_prop = 'test'; } $r = function(Example1 $e){ return $e->_prop; }; $a = new Example1(); $rfp = new ReflectionProperty('Example1','_prop'); $rfp->setAccessible(true); var_dump($rfp->getValue($a)); //结果输出:string 'test' (length=4) ?>
2. Using Closure::bind ()
This method is new in PHP 5.4.0.
class Example1{ private $_prop = 'test'; } $r = function(Example1 $e){ return $e->_prop; }; $a = new Example1(); $r = Closure::bind($r,null,$a); var_dump($r($a)); //结果输出:string 'test' (length=4) ?>
Alternatively, we can access it in a reference way so that we can modify the private properties of the class:
class Example1{ private $_prop = 'test'; } $a = new Example1(); $r = Closure::bind(function & (Example1 $e) { return $e->_prop; }, null, $a); $cake = & $r($a); $cake = 'lie'; var_dump($r($a)); //结果输出:string 'lie' (length=3)
Thus, we can encapsulate a function to read/set the private properties of the class:
$reader = function & ($object, $property) { $value = & Closure::bind(function & () use ($property) { return $this->$property; }, $object, $object)->__invoke(); return $value; }; ?>
Closure::bind () also has a very useful feature that we can use to give a dynamic way of adding a class. An example of this is given in the official documentation:
Trait Metatrait {Private $Methods=Array(); Public functionAddmethod ($MethodName,$methodcallable) {if(!is_callable ($methodcallable)) {Throw NewInvalidArgumentException (' Second param must be callable '); }$ This->methods[$MethodName] = Closure::bind ($methodcallable,$ This, Get_class ()); } Public function__call ($MethodName,Array $args) {if(isset($ This->methods[$MethodName])) {returnCall_user_func_array ($ This->methods[$MethodName],$args); }ThrowRuntimeException (' There is no method with the given name to call '); } }classHackthursday { Usemetatrait;Private $DayOfWeek=' Thursday '; }$Test=NewHackthursday ();$Test->addmethod ("Addedmethod",function(){return ' I was added in a dynamic way '; });Echo $Test->addedmethod ();//Result output: I was added in a dynamic way ?>
The above is introduced in PHP class outside Access class private properties of the method, including the aspects of the content, I hope to be interested in PHP tutorial friends helpful.