In php, how does one modify the private or protected attribute values of a class externally? in the unit test framework, I found a depressing problem: the tester needs to modify the private or protected member variable & #20540; of the class outside the class, and these variables are not abstracted into public attributes, and for the sake of the amount of code, it is also impossible to modify how to modify the private or protected attribute values of the class externally in php.
The unit test framework found a depressing problem: the tester needs to modify the value of the private or protected member variable of the class outside the class, these variables are not abstracted into public attributes, and the class to be tested cannot be modified for the sake of the amount of code. How can I modify private variables of a class outside the class? See the following key code:
Class file sellAction. php, the content is as follows:
cUid;echo "
";echo "output private id :".$this->id;echo "
";echo "output public pId:".$this->pId;echo "
";}}
The test. php file contains the following content:
$val) { $pro = $reflectCls->getProperty($key);if($pro && ($pro->isPrivate() || $pro->isProtected())){$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 "
";print_r($attr);echo "
";echo "
";echo "set private protect public var ";echo "
";var_dump($act);echo "
";$act->output();
In the browser, directly browse test. php. the content is roughly as follows:
not set private protect public varobject(SellAction)#1 (3) { ["cUid":protected]=> NULL ["id":"SellAction":private]=> NULL ["pId"]=> NULL } output protected cUid :output private id :output public pId:Array ( [cUid] => 234556 [pId] => 987676757 [id] => 782100 ) set private protect public var object(SellAction)#1 (3) { ["cUid":protected]=> string(6) "234556" ["id":"SellAction":private]=> string(6) "782100" ["pId"]=> string(9) "987676757" } output protected cUid :234556output private id :782100output public pId:987676757
The demo above mainly implements this function through reflection. Reflection features require php version> = 5.3, for reflection-related information, see: http://php.net/manual/en/book.reflection.php