Guest User

Untitled

a guest
Jul 21st, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. <?php
  2.  
  3. class DynamicObject {
  4.  
  5. /**
  6. * @var DynamicObject
  7. */
  8. public $prototype;
  9.  
  10. public function __construct(array $attributes = array()) {
  11. foreach ($attributes as $name => $value) {
  12. $this->$name = $value;
  13. }
  14. }
  15.  
  16. public function __get($varName) {
  17. if (!isset($this->$varName)) {
  18. return $this->prototype->$varName;
  19. }
  20. }
  21.  
  22. public function __call($methodName, $params) {
  23. array_unshift($params, $this);
  24. if (isset($this->$methodName)) {
  25. return call_user_func_array($this->$methodName, $params);
  26. } else {
  27. return call_user_func_array($this->prototype->$methodName, $params);
  28. }
  29. }
  30.  
  31. public static function extend(DynamicObject $prototype, $attributes = array()) {
  32. $child = new self($attributes);
  33. $child->prototype = $prototype;
  34. return $child;
  35. }
  36.  
  37. }
  38.  
  39. $animal = new DynamicObject(array(
  40. 'age' => 0,
  41. 'name' => 'El Barto',
  42. 'breathe' => function($me) {
  43. echo $me->name . " is breathing<br/>";
  44. }
  45. ));
  46.  
  47.  
  48. $animal->breathe(); // Echo: El Barto is breathing
  49.  
  50. ///////////////////////////////////////////////////////////////////////////////
  51. // Prototypal inheritance: an object extend another object
  52. //
  53.  
  54. $cat = DynamicObject::extend($animal, array(
  55. 'breathe' => function($me) {
  56. echo $me->name . " is purring<br/>";
  57. }
  58. ));
  59.  
  60. $cat->breathe(); // Echo: El Barto is purring
  61.  
  62.  
  63. // Modifyng the prototype dynamically change the child too
  64.  
  65. $animal->eat = function($me){
  66. echo 'Gnam!<br/>';
  67. };
  68.  
  69. $cat->eat(); // Echo: Gnam
Add Comment
Please, Sign In to add comment