Skip to content

Instantly share code, notes, and snippets.

@E1101
Created May 24, 2014 10:28
Show Gist options
  • Save E1101/53c09cdc6927b80b9da6 to your computer and use it in GitHub Desktop.
Save E1101/53c09cdc6927b80b9da6 to your computer and use it in GitHub Desktop.
Add methods on the fly to an object.
<?php
trait MetaTrait
{
private $methods = array();
public function addMethod($methodName, $methodCallable)
{
if (!is_callable($methodCallable)) {
throw new InvalidArgumentException('Second param must be callable');
}
$this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
}
public function __call($methodName, array $args)
{
if (isset($this->methods[$methodName])) {
return call_user_func_array($this->methods[$methodName], $args);
}
throw RunTimeException('There is no method with the given name to call');
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment