Skip to content

Instantly share code, notes, and snippets.

@galen
Last active December 14, 2015 22:28
Show Gist options
  • Save galen/5158086 to your computer and use it in GitHub Desktop.
Save galen/5158086 to your computer and use it in GitHub Desktop.
Dynamically add methods to objects with Closure:::bind
Trait Addable {
private $methods = array();
public function addMethod( $name, $callable ) {
$this->methods[$name] = Closure::bind( $callable, $this, get_class() );
}
public function __call( $method, array $args ) {
call_user_func_array( $this->methods[$method], $args );
}
}
Class Dog {
use Addable;
const LEGS = 4;
private $noise = 'Bark!';
}
$dog = new Dog;
$dog->addMethod(
'speak',
function(){
echo $this->noise . ' I have ' . self::LEGS . ' legs.';
}
);
$dog->speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment