Created
September 26, 2012 15:55
-
-
Save francescoagati/3788841 to your computer and use it in GitHub Desktop.
metaprogramming php: using define_method with traits, closure and rebind
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
<?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