Dynamic PHP Properties


/ Published in: PHP
Save to your folder(s)

This is a class/demonstration for creating dynamic properties and storing them in an array


Copy this code and paste it in your HTML
  1. class AbstractModel {
  2. private $data = array();
  3.  
  4. protected function __set($name, $value) {
  5. $this->data[$name] = $value;
  6. }
  7.  
  8. protected function __get($name) {
  9. if (array_key_exists($name, $this->data)) {
  10. return $this->data[$name];
  11. }
  12. return null;
  13. }
  14.  
  15. protected function __isset($name) {
  16. return isset($this->data[$name]);
  17. }
  18.  
  19. protected function __unset($name) {
  20. unset($this->data[$name]);
  21. }
  22.  
  23. public function printOut()
  24. {
  25. echo "<pre>";
  26. print_r($this);
  27. echo "</pre>";
  28. }
  29. }
  30. class User extends AbstractModel {
  31.  
  32. }
  33.  
  34. // how to use
  35.  
  36. $person = new User();
  37.  
  38. $person->name = 'John';
  39. $person->age = 26;
  40. $person->address = "217 Ziller's road brooklyn NY 11553";
  41. $person->printOut();
  42.  
  43. $car = new User();
  44. $car->make = 'Honda';
  45. $car->model = 'Civic';
  46. $car->cylinder = 6;
  47. $car->transmission = 'Automatic';
  48. $car->year = 2006;
  49.  
  50. $truck = new User();
  51. $truck->make = 'Ford';
  52. $truck->model = 'F-150';
  53. $truck->cylinder = 12;
  54. $truck->transmission = 'Manual';
  55. $truck->year = 2006;
  56.  
  57.  
  58. $person->car = array('honda' =>$car, 'Ford' => $truck);
  59.  
  60. $person->printOut();
  61.  
  62.  
  63. //output
  64. User Object
  65. (
  66. [data:private] => Array
  67. (
  68. [name] => John
  69. [age] => 26
  70. [address] => 217 Ziller's road brooklyn NY 11553
  71. )
  72.  
  73. )
  74.  
  75. User Object
  76. (
  77. [data:private] => Array
  78. (
  79. [name] => John
  80. [age] => 26
  81. [address] => 217 Ziller's road brooklyn NY 11553
  82. [car] => Array
  83. (
  84. [honda] => User Object
  85. (
  86. [data:private] => Array
  87. (
  88. [make] => Honda
  89. [model] => Civic
  90. [cylinder] => 6
  91. [transmission] => Automatic
  92. [year] => 2006
  93. )
  94.  
  95. )
  96.  
  97. [Ford] => User Object
  98. (
  99. [data:private] => Array
  100. (
  101. [make] => Ford
  102. [model] => F-150
  103. [cylinder] => 12
  104. [transmission] => Manual
  105. [year] => 2006
  106. )
  107.  
  108. )
  109.  
  110. )
  111.  
  112. )
  113.  
  114. )

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.