Methods for accessing class private properties outside of class in PHP

Source: Internet
Author: User

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.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.