feiyuanqiu
2016-12-01 20:27:05 +08:00
class Test
{
private $dynamicMethods = [];
public function __get($name)
{
return isset($this->dynamicMethods[ $name ]) ? $this->dynamicMethods[ $name ] : null;
}
public function __set($name, $value)
{
if ($this->isClosure($value)) {
$this->dynamicMethods[ $name ] = Closure::bind($value, $this, self::class);;
}
}
private function isClosure($value)
{
return is_callable($value) && get_class($value) === \Closure::class;
}
public function __isset($name)
{
return isset($this->dynamicMethods[ $name ]);
}
public function __call($name, $arguments)
{
if (!isset($this->dynamicMethods[ $name ])) {
trigger_error('Call to undefined method ' . self::class . "::{$name}", E_USER_ERROR);
}
return call_user_func($this->dynamicMethods[ $name ], $arguments);
}
}
$a = new Test();
$a->test = function () {
var_dump($this->dynamicMethods);
};
$a->test();