Created
March 6, 2015 16:59
-
-
Save lisachenko/f1e011685289c77b4324 to your computer and use it in GitHub Desktop.
Method accessor as closures
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
class MagicMethodAccessor { | |
public function test() | |
{ | |
echo 'Cool'; | |
} | |
final public function __get($name) | |
{ | |
if (method_exists($this, $name)) { | |
$method = (new ReflectionMethod($this, $name))->getClosure($this); | |
return $method; | |
} | |
return null; | |
} | |
final public function __call($name, $arguments) | |
{ | |
$method = $this->$name; | |
$rebind = Closure::bind($method, $this, get_called_class()); | |
return call_user_func_array($rebind, $arguments); | |
} | |
} | |
$obj = new MagicMethodAccessor(); | |
$method = $obj->test; // Will return closure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment