Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created April 25, 2013 00:32
Show Gist options
  • Save ackintosh/5456690 to your computer and use it in GitHub Desktop.
Save ackintosh/5456690 to your computer and use it in GitHub Desktop.
Dynamically adding methods in PHP
<?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