php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81611 ArgumentCountError when getting default value from ReflectionParameter with new
Submitted: 2021-11-11 08:44 UTC Modified: 2021-11-12 09:33 UTC
From: ondrej at mirtes dot cz Assigned:
Status: Closed Package: Reflection related
PHP Version: 8.1.0RC5 OS: N/A
Private report: No CVE-ID: None
 [2021-11-11 08:44 UTC] ondrej at mirtes dot cz
Description:
------------
Trying to get a default value from ReflectionParameter when the default value contains "new" leads to "Uncaught ArgumentCountError: ReflectionParameter::__construct() expects exactly 2 arguments, 0 given" from an internal function.

Test script:
---------------
<?php // lint >= 8.1

namespace NewInInitializers;

class Foo
{

	public function doFoo(
		object $test = new self()
	): object
	{
		return $test;
	}

}

class Bar extends Foo
{

}

$ref = new \ReflectionClass(Foo::class);
$params = $ref->getMethod('doFoo')->getParameters();
foreach ($params as $param) {
    var_dump($param->getDefaultValue());
}

Expected result:
----------------
object(NewInInitializers\Foo)#1 (0) {
}

Actual result:
--------------
Fatal error: Uncaught ArgumentCountError: ReflectionParameter::__construct() expects exactly 2 arguments, 0 given in /in/aJ2qI:25
Stack trace:
#0 [internal function]: ReflectionParameter->__construct()
#1 /in/aJ2qI(25): ReflectionParameter->getDefaultValue()
#2 {main}
  thrown in /in/aJ2qI on line 25

Process exited with code 255.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-11-12 03:27 UTC] camporter1 at gmail dot com
The issue seems to be that the scope is not correct when the class is determined when evaluating new self().

A hacky patch would be https://gist.github.com/camporter/0fe6df7909c2473323f6892ced78fb62
which allows zend_ast_fetch_class to provide the scope it was given rather than relying on the current executed scope.
 [2021-11-12 09:33 UTC] nikic@php.net
@camporter1: Your patch looks reasonable to me, would you like to submit a PR?
 [2021-11-12 17:37 UTC] camporter1 at gmail dot com
@nikic Sure, I'll have one ready in a few hours.
 [2021-11-12 22:51 UTC] camporter1 at gmail dot com
Created https://github.com/php/php-src/pull/7649
 [2021-11-16 13:40 UTC] git@php.net
Automatic comment on behalf of camporter (author) and nikic (committer)
Revision: https://github.com/php/php-src/commit/812df2bd8a95c7e07879924b023e14c2dbe1c24f
Log: Fix bug #81611
 [2021-11-16 13:40 UTC] git@php.net
-Status: Open +Status: Closed
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 10:01:29 2024 UTC