php-src icon indicating copy to clipboard operation
php-src copied to clipboard

ReflectionParameter::isDefaultValueAvailable() returns false negative if next parameter is not optional.

Open pronode opened this issue 4 years ago • 2 comments

Description

The following code:

class Test {
	
	public function foo(int $id = 1, string $str = 'default') {}
	public function goo(int $id = 1, string $str) {}
	public function moo(int $id = 1) {}
}

var_dump((new \ReflectionMethod(new Test(), 'foo'))->getParameters()[0]->isDefaultValueAvailable());
var_dump((new \ReflectionMethod(new Test(), 'goo'))->getParameters()[0]->isDefaultValueAvailable());
var_dump((new \ReflectionMethod(new Test(), 'moo'))->getParameters()[0]->isDefaultValueAvailable());

Resulted in this output:

bool(true) bool(false) bool(true)

But I expected this output instead:

bool(true) bool(true) bool(true)

PHP Version

PHP 8.1.1

Operating System

Windows 10

pronode avatar Feb 13 '22 13:02 pronode

I think it messes up logic with ReflectionParameter::isOptional() in some way.

pronode avatar Feb 13 '22 13:02 pronode

Hi @pronode. This is by design.

https://3v4l.org/Za9kK#v8.1.2

class Test {
	public function foo(int $id = 1, string $str) {}
	public function bar(int $id = 1, string $str = '') {}
}

var_dump((string) new \ReflectionMethod(new Test(), 'foo'));
var_dump((string) new \ReflectionMethod(new Test(), 'bar'));
Deprecated: Optional parameter $id declared before required parameter $str is implicitly treated as a required parameter in /in/Za9kK on line 4
string(171) "Method [ <user> public method foo ] {
  @@ /in/Za9kK 4 - 4

  - Parameters [2] {
    Parameter #0 [ <required> int $id ]
    Parameter #1 [ <required> string $str ]
  }
}
"
string(180) "Method [ <user> public method bar ] {
  @@ /in/Za9kK 5 - 5

  - Parameters [2] {
    Parameter #0 [ <optional> int $id = 1 ]
    Parameter #1 [ <optional> string $str = '' ]
  }
}
"

"is implicitly treated as a required parameter" means that the default value is implicitly dropped. You can't actually make use of the default value in any way, not even with named parameters. Hope that clear it up for you.

iluuu1994 avatar Feb 13 '22 14:02 iluuu1994