php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #81386 ReflectionProperty::getDefaultValue() and promoted properties
Submitted: 2021-08-26 10:30 UTC Modified: 2021-08-26 10:35 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: enumag at gmail dot com Assigned:
Status: Open Package: Documentation problem
PHP Version: 8.0.9 OS:
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2021-08-26 10:30 UTC] enumag at gmail dot com
Description:
------------
Currently when you declare a promoted property with a default value the ReflectionProperty::getDefaultValue() won't return that value.

I'm not sure if this behavior is expected or not but in either case something needs to be changed.

If this behavior is unexpected then it should be fixed to return the correct value.

If this behavior is expected then the documentation of ReflectionProperty::getDefaultValue() should mention this drawback along with a few lines of code how to get to the relevant ReflectionParameter and get the value there.

Test script:
---------------
<?php

class X {
    public function __construct(
        public bool $y = false
    ) {
    }
}

var_export((new ReflectionProperty('X', 'y'))->getDefaultValue());

Expected result:
----------------
Either the value should be returned or this behavior needs to be documented.

Actual result:
--------------
The default value is not returned and there is no mention of this behavior in the documentation

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-08-26 10:33 UTC] enumag at gmail dot com
Forgot to mention: ReflectionProperty::hasDefaultValue() needs to be fixed or better documented as well.
 [2021-08-26 10:35 UTC] nikic@php.net
-Type: Bug +Type: Documentation Problem
 [2021-08-26 10:35 UTC] nikic@php.net
Promoted properties intentionally don't have a default value. The property is always initialized by the constructor.

I don't think this needs to be mentioned in the ReflectionProperty::getDefaultValue() docs, as reflection simply reflects reality. However, it should be mentioned in the promoted property docs at https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion.
 [2021-08-26 10:45 UTC] enumag at gmail dot com
@nikic I have to disagree. As a programmer who is using promoted properties I don't differentiate if the default value is for the property or the parameter. Even if the behavior is expected from the language's point of view, it's not entirely expected from the user's point of view. I'd much rather see it mentioned there than only randomly stumbling on it while debugging.
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Mon Oct 25 08:03:33 2021 UTC