Skip to content

Instantly share code, notes, and snippets.

@tristanlins
Last active December 23, 2015 07:09
Show Gist options
  • Save tristanlins/6598433 to your computer and use it in GitHub Desktop.
Save tristanlins/6598433 to your computer and use it in GitHub Desktop.
PHP Prototype Theory
<?php
class APrototypedClass extends Prototype
{
}
APrototypedClass::$prototype['getId'] = function() {
return $this->id;
};
APrototypedClass::$prototype['setId'] = function($id) {
$this->id = $id;
};
<?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]);
}
}
<?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