Created
April 25, 2013 00:32
-
-
Save ackintosh/5456690 to your computer and use it in GitHub Desktop.
Dynamically adding methods in PHP
This file contains hidden or 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
<?php | |
class DynamicMethod | |
{ | |
protected $dynamic_methods = array(); | |
public function __call($name, $args) | |
{ | |
if ($this->dynamic_methods[$name]) { | |
return call_user_func_array($this->dynamic_methods[$name], $args); | |
} | |
super($name, $args); | |
} | |
public function define_method($name, $method) | |
{ | |
if (!is_callable($method)) throw new RuntimeException(); | |
$this->dynamic_methods[$name] = $method; | |
} | |
} | |
$df = new DynamicMethod(); | |
$df->define_method('echo_hoge', function () { echo 'hoge' . PHP_EOL; }); | |
$df->echo_hoge();// hoge | |
$df->define_method('multi', function ($a, $b) { return $a * $b; }); | |
echo $df->multi(3, 4);// 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment