LoginSignup
10
11

More than 5 years have passed since last update.

シンプルなデリゲートの実装

Posted at

C#ライクなデリゲートの実装

<?php

class Delegate
{
    /** @var callable[] */
    protected $callbacks = [];

    /**
     * Add callback function
     * @param callable $callback
     * @return $this
     */
    public function add(callable $callback)
    {
        $this->callbacks[] = $callback;
        return $this;
    }

    /**
     * Remove callback function
     * @param callable $callback
     * @return $this
     */
    public function remove(callable $callback)
    {
        foreach ( $this->callbacks as $key => $_callback )
        {
            if ( $callback == $_callback )
            {
                unset($this->callbacks[$key]);
                return $this;
            }
        }
        return $this;
    }

    /**
     * Invoke callback functions
     * @return mixed
     */
    public function __invoke()
    {
        $result = null;

        foreach ( $this->callbacks as $callback )
        {
            $result = call_user_func_array($callback, func_get_args());
        }

        return $result;
    }
}

$callback = function($name) {
    echo "Hello $name", PHP_EOL;
};

$delegate = new Delegate();
$delegate
    ->add($callback)
    ->add($callback)
    ->remove($callback);

$delegate("World");
10
11
1

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
10
11