Last active
December 14, 2015 22:28
-
-
Save galen/5158086 to your computer and use it in GitHub Desktop.
Dynamically add methods to objects with Closure:::bind
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 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