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

`ReflectionClass::newInstance` and `ReflectionClass::newInstanceArgs` are not strict

Open roxblnfk opened this issue 4 years ago • 3 comments

Description

The following code:

<?php

declare(strict_types=1);

class Foo {    
    public function __construct(
        public bool $bool,
        public int $int,
    ) {}
}
$args = ['bar', '10'];

$reflection = new \ReflectionClass(Foo::class);
$constructor = $reflection->getConstructor();
$instance = $reflection->newInstance(...$args);

var_dump($instance);

Resulted in this output:

object(Foo)#3 (2) {
  ["bool"]=>
  bool(true)
  ["int"]=>
  int(10)
}

But I expected this output instead:

TypeError: Foo::__construct(): Argument #1 ($bool) must be of type bool, string given

Sandbox: https://3v4l.org/KtY24

PHP Version

8.0, 8.1

Operating System

No response

roxblnfk avatar Apr 21 '22 09:04 roxblnfk

https://3v4l.org/r7atB

This has been like this since strict_types are supported. The constructor is called from the internal newInstance method which does not have strict_types enabled. Similarly, something like array_map will invoke the closure without strict_types and thus do type coercion.

https://3v4l.org/isV9d

declare(strict_types=1);

array_map(function (string $i) {
    var_dump($i);
}, [1, 2, 3]);

string(1) "1" string(1) "2" string(1) "3"

I think it's not completely unreasonable to expect strict_types to be applied to internal functions but it would also be a large BC break.

iluuu1994 avatar Apr 21 '22 10:04 iluuu1994

Related: https://bugs.php.net/bug.php?id=74750

iluuu1994 avatar Apr 21 '22 10:04 iluuu1994

Given the comment on bugs.php.net I'm closing this issue. I think this would not be an unreasonable change but definitely one that would require an RFC. https://wiki.php.net/rfc/howto Thanks for the report!

iluuu1994 avatar Apr 21 '22 10:04 iluuu1994