Advertisement
Guest User

Untitled

a guest
Sep 5th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. <?php
  2.  
  3. // once you add the magical setter and getter
  4. // you can can access any private fields as usual
  5. // but you can also develop custom setter and getter if you want
  6. $user = new MagicUser();
  7. $user->username = "test";
  8. $user->password = "pass";
  9. echo $user->username; // will print Test not test.
  10.  
  11. // magical setter and getter
  12. class MagicUser{
  13. private $username;
  14.  
  15. private $password;
  16.  
  17. public function setUsername($username){
  18. $this->username = ucfirst($username);
  19. }
  20.  
  21. public function __set($name , $value){
  22. $setter = 'set'.ucfirst($name);
  23. if(method_exists($this,$setter)){
  24. $this->$setter($value);
  25. }else{
  26. $this->$name = $value;
  27. }
  28. }
  29.  
  30. public function __get($name){
  31. $getter = 'get'.ucfirst($name);
  32. if(method_exists($this,$getter)){
  33. return $this->$getter();
  34. }else{
  35. return $this->$name;
  36. }
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement