php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81258 Strict mode not working with reflection
Submitted: 2021-07-14 13:27 UTC Modified: 2021-07-14 14:06 UTC
From: roke22 at gmail dot com Assigned:
Status: Open Package: Unknown/Other Function
PHP Version: 8.0.8 OS: Linux
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2021-07-14 13:27 UTC] 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);


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-07-14 13:39 UTC] nikic@php.net
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.
 [2021-07-14 14:06 UTC] roke22 at gmail dot com
excuse my ignorance, could you give a simple example? Maybe using the case of the example script.
 
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Thu Dec 01 14:05:55 2022 UTC