php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #78411 Typed properties not working as expected when instantiated via reflection.
Submitted: 2019-08-13 20:15 UTC Modified: 2019-08-13 20:51 UTC
From: tandrewbennett at hotmail dot com Assigned:
Status: Duplicate Package: *General Issues
PHP Version: 7.4.0beta2 OS: Ubuntu 16.04
Private report: No CVE-ID: None
 [2019-08-13 20:15 UTC] tandrewbennett at hotmail dot com
Description:
------------
When instantiating an object using reflectionClass::newInstanceWithoutConstructor, assigning values to uninitialized typed properties has no effect.

Test script:
---------------
class Foo
{
    protected string $bar;
    protected string $baz;
    protected string $qux = 'initial qux';

    public function fillValues()
    {
        $this->bar = 'bar';
        $this->baz = 'baz';
        $this->qux = 'qux';
    }

    public function getBar()
    {
        return $this->bar;
    }

    public function getBaz()
    {
        return $this->baz;
    }

    public function getQux()
    {
        return $this->qux;
    }
}

$rc = new ReflectionClass(Foo);
$foo = $rc->newInstanceWithoutConstructor();
$foo->fillValues();
echo $foo->getBar() . PHP_EOL;
echo $foo->getBaz() . PHP_EOL;
echo $foo->getQux() . PHP_EOL;

Expected result:
----------------
bar
baz
qux

Actual result:
--------------
Fatal error: Uncaught Error: Typed property Foo::$bar 
must not be accessed before initialization

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-08-13 20:25 UTC] nikic@php.net
-Status: Open +Status: Feedback
 [2019-08-13 20:25 UTC] nikic@php.net
Can't reproduce: https://3v4l.org/U8t8M Same result on current 7.4 HEAD.
 [2019-08-13 20:48 UTC] tandrewbennett at hotmail dot com
I'm sorry Nikita. I copied and pasted the example script from an entity that I created when testing in a real world app. I just read through the RFC (trying t figure out what's causing this) and realized that uninitialized typed properties are being passed through __SET() when assigning values to them (even when assigned from within an instance method inside the class)? I didn't realize this was the case (my base entity class makes use of the __SET() method) and that seems to be what was causing this). I'm sorry for the confusion, I didn't expect __SET() to be invoked when I was assigning properties from within the scope of the class itself (not from the outside).
 [2019-08-13 20:51 UTC] nikic@php.net
-Status: Feedback +Status: Duplicate
 [2019-08-13 20:51 UTC] nikic@php.net
Yeah, the __set() behavior is a known issue, unclear what we should do about that. Marking this as a duplicate of bug #78226.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Dec 12 04:01:27 2024 UTC