LoginSignup
0
0

More than 3 years have passed since last update.

【PHP】PHP7でも「名前付き引数」を使いたくて作ってみた

Posted at

使う場面はなかなかないだろうけれど、やっつけしてみた

<?php
class Hoge
{
    public function __call($name, $arguments)
    {
        $funcRef = new ReflectionMethod($this, $name);
        $parameters = $funcRef->getParameters();

        $createNewArguments = false;

        if (count($arguments) == 1) {
            if (count($parameters) == 1 && isset($arguments[0][$parameters[0]->name])) {
                $createNewArguments = true;
            } elseif (count($parameters) != 1) {
                $createNewArguments = true;
            }
        }

        if ($createNewArguments) {
            $arguments = $arguments[0];
            foreach ($parameters as $param) {
                if (isset($arguments[$param->name])) {
                    $newArgs[] = $arguments[$param->name];
                } else {
                    var_dump($param->isDefaultValueAvailable());
                    if ($param->isDefaultValueAvailable()) {
                        $newArgs[] = $param->getDefaultValue();
                    } else {
                        throw new Exception('引数$'.$param->name.'が定義されていません');
                    }
                }
            }
            call_user_func_array([$this, $name], $newArgs);
        } else {
            call_user_func_array([$this, $name], $arguments);
        }
    }

    protected function test($a, $b = 'test', $c)
    {
        var_dump([
            'a' => $a,
            'b' => $b,
            'c' => $c,
        ]);
    }
}

$class = new Hoge();
$class->test([
//    'b' => 'bbb',
    'a' => 'aaa',
    'c' => 'ccc',
]);

$class->test('123', '234', '345');

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