fork download
  1. <?php
  2. class User {
  3. public $name = 'Adrian';
  4. protected $ssn = 'XXX-AA-YYY';
  5. private $salary = 5400.00;
  6. }
  7.  
  8. $user = new User();
  9. echo$user->name;
  10. //echo$user->ssn;
  11. //echo$user->salary;
  12.  
  13. var_dump($user);
  14.  
  15.  
  16. $reflector = new ReflectionClass('User');
  17.  
  18. foreach($reflector->getProperties() as $prop) {
  19.  
  20. $prop->setAccessible(true);
  21.  
  22. if($prop->getName() == 'name') $prop->setValue($user, 'Alice');
  23. if($prop->getName() == 'ssn') $prop->setValue($user, 'YYY-BB-YYY');
  24. if($prop->getName() == 'salary') $prop->setValue($user, 7000);
  25. }
  26.  
  27.  
  28. var_dump($user);
  29.  
  30.  
  31. ?>
Success #stdin #stdout 0.02s 24060KB
stdin
Standard input is empty
stdout
Adrianobject(User)#1 (3) {
  ["name"]=>
  string(6) "Adrian"
  ["ssn":protected]=>
  string(10) "XXX-AA-YYY"
  ["salary":"User":private]=>
  float(5400)
}
object(User)#1 (3) {
  ["name"]=>
  string(5) "Alice"
  ["ssn":protected]=>
  string(10) "YYY-BB-YYY"
  ["salary":"User":private]=>
  int(7000)
}