<?php
trait MethodAttachable
{
protected $_callbacks = array();
public function __set($name, $value)
{
if (is_callable($value)) {
$this->_callbacks[$name] = $value;
}
$this->{$name} = $value;
}
public function magicCallMethodAttachable($method, $args)
{
if (isset($this->_callbacks[$method])) {
$callback = $this->_callbacks[$method];
if ($callback instanceof \Closure) {
$callback = \Closure::bind($callback, $this, get_class($this));
}
return call_user_func_array($callback, $args);
}
throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s', get_class($this), $method));
}
public function __call($method, $args)
{
return $this->magicCallMethodAttachable($method, $args);
}
}
使い方:
<?php
class Foo
{
use MethodAttachable;
}
$foo = new Foo();
$foo->name = 'wozozo';
$foo->eat = function($food) {
echo sprintf('%s eats %s.', $this->name, $food), PHP_EOL;
};
$foo->eat('cocoiti');