Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DynamicObject {
- /**
- * @var DynamicObject
- */
- public $prototype;
- public function __construct(array $attributes = array()) {
- foreach ($attributes as $name => $value) {
- $this->$name = $value;
- }
- }
- public function __get($varName) {
- if (!isset($this->$varName)) {
- return $this->prototype->$varName;
- }
- }
- public function __call($methodName, $params) {
- array_unshift($params, $this);
- if (isset($this->$methodName)) {
- return call_user_func_array($this->$methodName, $params);
- } else {
- return call_user_func_array($this->prototype->$methodName, $params);
- }
- }
- public static function extend(DynamicObject $prototype, $attributes = array()) {
- $child = new self($attributes);
- $child->prototype = $prototype;
- return $child;
- }
- }
- $animal = new DynamicObject(array(
- 'age' => 0,
- 'name' => 'El Barto',
- 'breathe' => function($me) {
- echo $me->name . " is breathing<br/>";
- }
- ));
- $animal->breathe(); // Echo: El Barto is breathing
- ///////////////////////////////////////////////////////////////////////////////
- // Prototypal inheritance: an object extend another object
- //
- $cat = DynamicObject::extend($animal, array(
- 'breathe' => function($me) {
- echo $me->name . " is purring<br/>";
- }
- ));
- $cat->breathe(); // Echo: El Barto is purring
- // Modifyng the prototype dynamically change the child too
- $animal->eat = function($me){
- echo 'Gnam!<br/>';
- };
- $cat->eat(); // Echo: Gnam
Add Comment
Please, Sign In to add comment