0

Is there a way to call the below method, but only specify the params at the end, and use the defaults for the other params?

$published = true;
$this->display($published);


public function display($name = 'John', $date = 'December', $published = false){
    //$name = 'John'
    //$date = 'December'
    //$published = true
}
panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

0

You can use reflection for that, example:

<?php

class A
{
    public function display($name = 'John', $date = 'December', $published = false)
    {
        var_dump($name, $date, $published);
    }

    public function test()
    {
        $args = [];
        $reflectionMethod = new ReflectionMethod($this, 'display');
        foreach($reflectionMethod->getParameters() as $parameter) {
            $args[$parameter->getName()] = $parameter->getDefaultValue();
        }
        $args['published'] = true;
        $reflectionMethod->invokeArgs($this, $args);
    }
}

(new A)->test();
Anton Ohorodnyk
  • 891
  • 5
  • 20