Last active
December 23, 2015 07:09
-
-
Save tristanlins/6598433 to your computer and use it in GitHub Desktop.
PHP Prototype Theory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class APrototypedClass extends Prototype | |
{ | |
} | |
APrototypedClass::$prototype['getId'] = function() { | |
return $this->id; | |
}; | |
APrototypedClass::$prototype['setId'] = function($id) { | |
$this->id = $id; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Prototype | |
{ | |
static public $prototype = array(); | |
private $properties = array(); | |
public function __call($method, $args) { | |
$closure = false; | |
if (isset($this->properties[$method])) { | |
$closure = $this->properties[$method]; | |
} | |
if (isset(static::$prototype[$method])) { | |
$closure = static::$prototype[$method]; | |
} | |
if ($closure) { | |
$closure = Closure::bind($closure, $this); | |
return call_user_func_array($closure, $args); | |
} | |
throw new \Exception('Method ' . $method . ' is undefined'); | |
} | |
public function __set($name, $value) | |
{ | |
$this->properties[$name] = $value; | |
} | |
public function __get($name) | |
{ | |
return $this->properties[$name]; | |
} | |
public function __isset($name) | |
{ | |
return isset($this->properties[$name]); | |
} | |
public function __unset($name) | |
{ | |
unset($this->properties[$name]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$object = new APrototypedClass(); | |
$object->setId(1); | |
echo $object->getId(); // display 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment