Last active
March 19, 2022 10:44
-
-
Save pjdevries/8a5c7d0fd5527d72a507626a7ea683cd to your computer and use it in GitHub Desktop.
Dynamic object methods (closure object binding)
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
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