Bug #81258 [Opn]: Strict mode not working with reflection
| From: | nikic@php.net | Date: | Wed, 14 Jul 2021 13:39:39 +0000 |
| Subject: | Bug #81258 [Opn]: Strict mode not working with reflection | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-235028@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=81258&edit=1
ID: 81258
Updated by: nikic@php.net
Reported by: roke22 at gmail dot com
Summary: Strict mode not working with reflection
Status: Open
Type: Bug
Package: Unknown/Other Function
Operating System: Linux
PHP Version: 8.0.8
Block user comment: N
Private report: N
New Comment:
Property assignments follow the strict_type directive of wherever the assignment is performed from.
In this case, it occurs from the ReflectionProperty::setValue() implementation, which is in
strict_types=0 mode (like all extension code). Thus type coercions are allowed.
A way to perform the assignment with strict type semantics would be by using closure rebinding.
Previous Comments:
------------------------------------------------------------------------
[2021-07-14 13:27:34] roke22 at gmail dot com
Description:
------------
Hello,
when you try to assign a value to a property of a DTO and it is not of the same type, it fails when
you do it normally.
However this does not happen when you use reflection, in this case try to convert it to the type of
the property making for example a 2 to be true for a bool property.
The expected behavior should be the same. This error throws all libraries about dto like https://github.com/spatie/data-transfer-object
because you can get the DTO with a true or false value in boolean properties where are invalid.
Test script:
---------------
This one fails and works ok
<?php
declare(strict_types=1);
class MyClassReflection {
public int $name;
}
$dt = new MyClassReflection();
$dt->name = "33";
var_dump($dt);
This one don't throw the exception but should throw the exception:
<?php
declare(strict_types=1);
class MyClassReflection {
public int $name;
}
$dt = new MyClassReflection();
$reflectionClass = new ReflectionClass('MyClassReflection');
$reflectionClass->getProperty('name')->setValue($dt, '33');
var_dump($dt);
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81258&edit=1