Created
May 24, 2014 10:28
-
-
Save E1101/53c09cdc6927b80b9da6 to your computer and use it in GitHub Desktop.
Add methods on the fly to an object.
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 | |
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