Skip to content

Instantly share code, notes, and snippets.

@francescoagati
Created September 26, 2012 15:55
Show Gist options
  • Save francescoagati/3788841 to your computer and use it in GitHub Desktop.
Save francescoagati/3788841 to your computer and use it in GitHub Desktop.
metaprogramming php: using define_method with traits, closure and rebind
<?php
trait MethodsRuntime {
public static function defineMethod($name,$fn) {
self::$methods[$name]=$fn;
}
function __call($method, $arguments) {
echo $method;
$fn=self::$methods[$method]->bindTo($this);
print_r($fn);
return call_user_func_array($fn,$arguments);
}
}
class A {
static $methods=[];
use MethodsRuntime;
function __construct() {
$this->c=100;
}
}
A::defineMethod("sum",function($a,$b) {
return $a + $b + $this->c;
});
echo (new A())->sum(1,2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment