Advertisement
Achilles

Magic methods for properties ( php )

Jul 12th, 2013
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. <?php
  2.  
  3. class Car
  4. {
  5.  
  6. public $manufacturer;
  7. public $model;
  8. public $color;
  9. private $_extraData = array();
  10.  
  11. /**
  12. * __get() gets called when code try to read invisible property
  13. * @param unknown $propertyName
  14. * @return multitype:|NULL
  15. */
  16. public function __get( $propertyName )
  17. {
  18. if( array_key_exists( $propertyName , $this->_extraData) )
  19. {
  20. return $this->_extraData[$propertyName];
  21. }
  22.  
  23. else
  24. {
  25. return null;
  26. }
  27. }
  28.  
  29. /**
  30. * __set() gets called when code try to write invsible property of the object
  31. * @param unknown $propertyName
  32. * @param unknown $propertyValue
  33. */
  34. public function __set( $propertyName , $propertyValue )
  35. {
  36. $this->_extraData[$propertyName] = $propertyValue;
  37.  
  38. echo "<pre>";
  39. print_r($this->_extraData);
  40. echo "</pre>";
  41. }
  42.  
  43. }
  44.  
  45. $myCar = new Car();
  46. $myCar->manufacturer = "Volkswagen";
  47. $myCar->model = "Beetle";
  48. $myCar->color = "red";
  49.  
  50. $myCar->engineSize = 1.8;
  51. $myCar->otherColors = array( "green" , "blue" , "purple" );
  52.  
  53. // var_dump( $myCar->otherColors );
  54.  
  55. var_dump( property_exists( "Car" , 'engineSize' ) );
  56. var_dump( property_exists( "Car" , 'color' ) );
  57.  
  58.  
  59. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement