Skip to content

Instantly share code, notes, and snippets.

@pjdevries
Last active March 19, 2022 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjdevries/8a5c7d0fd5527d72a507626a7ea683cd to your computer and use it in GitHub Desktop.
Save pjdevries/8a5c7d0fd5527d72a507626a7ea683cd to your computer and use it in GitHub Desktop.
Dynamic object methods (closure object binding)
trait DynamicMethod
{
private array $dynamicMethods = [];
public function addMethod(string $methodName, callable $methodCallable): void
{
$this->dynamicMethods[$methodName] = Closure::bind($methodCallable, $this, get_class());
}
public function __call(string $methodName, ...$args)
{
if (isset($this->dynamicMethods[$methodName]))
{
return call_user_func($this->dynamicMethods[$methodName], $args);
}
throw new \RuntimeException(sprintf("Dynamic method does not exist: %s::%s", __CLASS__, $methodName));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment