php / php/php-src

[8.4] Widening property hook's type for promoted property does not work

Open
#16,638 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Feature Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The following code:

<?php

declare(strict_types=1);

class Foo
{
    public function __construct(
        public int $baz { set (int|string|stdClass $value) {
            if (is_int($value)) {
                $this->baz = $value;
            } else if ($value instanceof stdClass
                && property_exists($value, 'baz')
                && is_int($value->baz)
            ) {
                $this->baz = $value->baz;
            } else if (is_numeric($value)) {
                $this->baz = (int) $value;
            } else {
                throw new InvalidArgumentException('Invalid value');
            }
        } },
    ) {}
}

$obj = new stdClass();
$obj->baz = 123;

var_dump(new Foo($obj));

Resulted in this output:

Fatal error: Uncaught TypeError: Foo::__construct(): Argument #1 ($baz) must be of type int, stdClass given, called in /in/2mZY5 on line 29 and defined in /in/2mZY5:7
Stack trace:
#0 /in/2mZY5(29): Foo->__construct(Object(stdClass))
#1 {main}
  thrown in /in/2mZY5 on line 7

But I expect this to work instead, just like when property is not promoted.

Originally encountered when preparing Twitter thread.

PHP Version

8.4 (current master)

Operating System

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the promoted-property example in the issue and compare it with the non-promoted-property example linked there. Trace where the constructor argument is type-checked versus where the property hook handles assignment; done means the promoted case accepts the widened hook input as expected and has a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.