LoginSignup
11
9

More than 5 years have passed since last update.

オブジェクトに動的にメソッドを追加するトレイト

Last updated at Posted at 2012-04-05
<?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');
11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9