LoginSignup
0
0

More than 5 years have passed since last update.

動的methodを全てstaticで使用できるようにする方法

Posted at

composerで落としたライブラリを見てると動的methodを静的に変換する処理が多数実装されていたのでTraitにしてみました。

trait Dynamic2static
{
    public static function getInstance() : self
    {
        static $instance = null;
        if ($instance === null) {
            $instance = new self();
        }
        return $instance;
    }

    public static function __callStatic($method, $args)
    {
        $instance = static::getInstance();
        if (!is_callable([$instance, $method])) {
            // ここは変えたほうが良いです
            throw new Exception();
        }
        switch (count($args)) {
            case 0:
                return $instance->{$method}();

            case 1:
                return $instance->{$method}($args[0]);

            case 2:
                return $instance->{$method}($args[0], $args[1]);

            case 3:
                return $instance->{$method}($args[0], $args[1], $args[2]);

            case 4:
                return $instance->{$method}($args[0], $args[1], $args[2], $args[3]);

            default:
                return call_user_func_array([$instance, $method], $args);
        }
    }
}

Gitに上げようかとも思ったんですが、需要がなさそうだなって思ったので...

0
0
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
0
0