Skip to content

Instantly share code, notes, and snippets.

@imliam
Created January 10, 2018 18:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imliam/f430f289a87aa1304d754972271c7fb4 to your computer and use it in GitHub Desktop.
Save imliam/f430f289a87aa1304d754972271c7fb4 to your computer and use it in GitHub Desktop.
Trait to dynamically bind methods to a class.
<?php
trait BindMethods
{
private $boundMethods = [];
public function bindMethod($methodName, $method) {
$this->boundMethods[$methodName] = Closure::bind($method, $this, get_class());
}
function __call($method, $args) {
if (is_callable('parent::__call')) {
parent::__call($method, $args);
}
if(is_callable($this->boundMethods[$method]))
{
return call_user_func_array($this->boundMethods[$method], $args);
}
}
}
@imliam
Copy link
Author

imliam commented Jan 10, 2018

Example usage:

class ExampleClass
{
    use BindMethods;

    public function __construct($example)
    {
        $this->example = $example;
    }
}

$a = new ExampleClass('This is an');

$a->bindMethod('test', function() {
    return "{$this->example} example of using the trait.";
});

echo $a->test(); // Returns "This is an example of using the trait."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment