How to modify the private or protected property values of a class externally in PHP
When doing the unit testing framework, a rather depressing problem was found: testers need to modify the values of the class's private or protected member variables outside of the class, and those variables do not have properties that are abstracted as public, and for the sake of the code volume, it is not possible to modify the class to be tested. How do you modify the private variables of a class outside of the class? Take a look at the following key code:
class file sellaction.php, which reads as follows:
Cuid;echo "
"; echo" Output private ID: ". $this->id;echo"
"; echo" Output public pId: ". $this->pid;echo"
";}}
Test file test.php with the following content:
$val) {$pro = $reflectCls->getproperty ($key); if ($pro && ($pro->isprivate () | | $pro->is Protected ()) {$pro->setaccessible (true); $pro->setvalue ($reference, $val);} else{$reference $key = $val;} } return true; $act = new Sellaction (); echo "Not set private protect public Var"; Echo "
"; Var_dump ($act); $act->output (); $attr = Array (' cUid ' = ' 234556 ', ' pId ' = ' 987676757 ', ' id ' = ' 782100 '); Initreferenceattr ($act, $attr); echo "
";p Rint_r ($attr); echo"
"; Echo"
"; echo" set private protect public Var "; Echo"
"; Var_dump ($act); echo"
"; $act->output ();
In the browser, browse test.php directly, the content is as follows:
Not set private protect public varobject (sellaction) #1 (3) {["CUid":p rotected]=> NULL ["id": "sellaction":p rivate]=& Gt null ["pid"]=> null} output protected cuid:output private Id:output public Pid:array ([cUid] = 234556 [PId] =&G T 987676757 [id] = 782100) Set private protect public var object (sellaction) #1 (3) {["CUid":p rotected]=> string (6) "234556" ["id": "sellaction":p rivate]=> string (6) "782100" ["PId"]=> string (9) "987676757"} Output protected CUid: 234556output Private Id:782100output Public pid:987676757
The demo above mainly uses reflection to achieve this function. The reflection function requires PHP version >=5.3, for information about reflection, see: http://php.net/manual/en/book.reflection.php