Skip to content

Add method to ReflectionClass to instantiate with the same semantics as PDOStatement::fetchObject() #19401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
63 changes: 63 additions & 0 deletions ext/reflection/php_reflection.c
Original file line number Diff line number Diff line change
Expand Up @@ -5132,6 +5132,69 @@ ZEND_METHOD(ReflectionClass, newInstanceArgs)
}
/* }}} */

/* {{{ Returns an instance of this class whose properties are filled with the given data before the constructor is called */
ZEND_METHOD(ReflectionClass, newInstanceFromData)
{
reflection_object *intern;
zend_class_entry *ce;
int argc = 0;
HashTable *data, *args = NULL;
zend_function *constructor;
zend_string *key;
zval *val;

GET_REFLECTION_OBJECT_PTR(ce);

if (ce->type == ZEND_INTERNAL_CLASS) {
zend_throw_exception_ex(reflection_exception_ptr, 0, "Class %s is an internal class that cannot be instantiated from data", ZSTR_VAL(ce->name));
RETURN_THROWS();
}

ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_HT(data)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();

if (args) {
argc = zend_hash_num_elements(args);
}

if (UNEXPECTED(object_init_ex(return_value, ce) != SUCCESS)) {
RETURN_THROWS();
}

ZEND_HASH_FOREACH_STR_KEY_VAL(data, key, val) {
zend_update_property_ex(ce, Z_OBJ_P(return_value), key, val);
} ZEND_HASH_FOREACH_END();

const zend_class_entry *old_scope = EG(fake_scope);
EG(fake_scope) = ce;
constructor = Z_OBJ_HT_P(return_value)->get_constructor(Z_OBJ_P(return_value));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may throw for internal classes.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the same code used by newInstance and newInstanceArgs which I'm thinking of refactoring into a shared function to cut the duplication, so would make sense to handle instantiating internal classes there but could be considered a breaking change?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure whether that's really a BC break? It would be throwing an exception either way?

We had a discussion a while ago with @DanielEScherzer and I think @nielsdos that it would probably be better to do something to fix the semantics regarding failing get_constructor, as various other places assume that you can even just check the constructor pointer on the CE.

Probably the best solution is that if the constructor field on the CE is NULL it means that it is not instantiable, and to set that field for classes that do not have a constructor to the zend_pass_function (which is what get's "called" anyway in those cases) but the downside of this approach is that you stop getting useful errors telling you how to get such an object (e.g. curl_init() for CurlHandle objects)

Copy link
Author

@mattdinthehouse mattdinthehouse Aug 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see what you mean - because this method sets properties before calling constructors that can have weird (and potentially vulnerable) behaviour.

I've added a check for ce->type == ZEND_INTERNAL_CLASS similar to newInstanceWithoutConstructor() to prevent using newInstanceFromData() for internal classes entirely.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That discussion is at #17796

Just so that I understand the semantics correctly, is there any difference between the proposed function and something like (class is given as an argument but would be from $this)

function newInstanceFromData(string $class, array $data, array $args = []) {
	$ref = new ReflectionClass($class);
	$instance = $ref->newInstanceWithoutConstructor();

	foreach ($data as $propName => $val) {
		$propAccess = $ref->getProperty($propName);
		$propAccess->setValue($instance, $val);
	}
	
	$instance->__construct(...$args);
	
	return $instance;
}

EG(fake_scope) = old_scope;

/* Run the constructor if there is one */
if (constructor) {
if (!(constructor->common.fn_flags & ZEND_ACC_PUBLIC)) {
zend_throw_exception_ex(reflection_exception_ptr, 0, "Access to non-public constructor of class %s", ZSTR_VAL(ce->name));
zval_ptr_dtor(return_value);
RETURN_THROWS();
}

zend_call_known_function(
constructor, Z_OBJ_P(return_value), Z_OBJCE_P(return_value), NULL, 0, NULL, args);

if (EG(exception)) {
zend_object_store_ctor_failed(Z_OBJ_P(return_value));
RETURN_THROWS();
}
} else if (argc) {
zend_throw_exception_ex(reflection_exception_ptr, 0, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ZSTR_VAL(ce->name));
RETURN_THROWS();
}
}
/* }}} */

void reflection_class_new_lazy(INTERNAL_FUNCTION_PARAMETERS,
int strategy, bool is_reset)
{
Expand Down
2 changes: 2 additions & 0 deletions ext/reflection/php_reflection.stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,8 @@ public function newInstanceWithoutConstructor(): object {}
/** @tentative-return-type */
public function newInstanceArgs(array $args = []): ?object {}

public function newInstanceFromData(array $data, array $args = []): object {}

public function newLazyGhost(callable $initializer, int $options = 0): object {}

public function newLazyProxy(callable $factory, int $options = 0): object {}
Expand Down
9 changes: 8 additions & 1 deletion ext/reflection/php_reflection_arginfo.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

216 changes: 216 additions & 0 deletions ext/reflection/tests/ReflectionClass_newInstanceFromData_001.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
--TEST--
ReflectionClass::newInstanceFromData
--FILE--
<?php

class A
{
public int $a;
public string $b;

public function __construct($c, $d)
{
echo "In constructor of class A\n";
}
}

class B
{
public int $a;
public readonly string $b;
}

class C
{
}

#[\AllowDynamicProperties]
class D
{
}

class E
{
public function __construct(
public int $a,
public string $b,
)
{}
}

class F
{
public readonly int $a;

public function __construct(
public readonly string $b,
)
{}
}

class G
{
public readonly int $a;
public readonly string $b;

public function __construct()
{
$this->b = 456;
}
}

class H
{
public int $a {
set(int $value) => $value + 1;
}
}

class I
{
public int $a;

public int $b {
get => $this->a + 1;
set(int $value) {
$this->a = $value - 1;
}
}
}


$rcA = new ReflectionClass('A');
$rcB = new ReflectionClass('B');
$rcC = new ReflectionClass('C');
$rcD = new ReflectionClass('D');
$rcE = new ReflectionClass('E');
$rcF = new ReflectionClass('F');
$rcG = new ReflectionClass('G');
$rcH = new ReflectionClass('H');
$rcI = new ReflectionClass('I');

// assign bad data type to normal class
try
{
$rcA->newInstanceFromData(['a' => 'bad', 'b' => 123], ['foo', 1337]);
echo "you should not see this\n";
}
catch(Throwable $e)
{
echo "Exception: " . $e->getMessage() . "\n";
}

// normal class with constructor
var_dump($rcA->newInstanceFromData(['a' => 123, 'b' => 'good'], ['foo', 1337]));

// normal class with no constructor and a readonly property
var_dump($rcB->newInstanceFromData(['a' => 123, 'b' => 'good']));

// trying to set dynamic properties on class without AllowDynamicProperties attribute
var_dump($rcC->newInstanceFromData(['a' => 123, 'b' => 'good'])); // this should warn
var_dump($rcC->newInstanceFromData([])); // this is fine

// setting dynamic properties on a class with AllowDynamicProperties attribute
var_dump($rcD->newInstanceFromData(['a' => 123, 'b' => 'good']));

// class with property promotion
try
{
$rcE->newInstanceFromData(['a' => 123, 'b' => 'good']); // no constructor args will fail
echo "you should not see this\n";
}
catch(Throwable $e)
{
echo "Exception: " . $e->getMessage() . "\n";
}

var_dump($rcE->newInstanceFromData(['a' => 123, 'b' => 'good'], [456, 'foo'])); // constructor args will override class props

// class with readonly promoted property
var_dump($rcF->newInstanceFromData(['a' => 123], ['b' => 'good']));

// readonly property set in the constructor
try
{
$rcG->newInstanceFromData(['a' => 123, 'b' => 'good']); // setting $b by data will conflict with constructor's set
echo "you should not see this\n";
}
catch(Throwable $e)
{
echo "Exception: " . $e->getMessage() . "\n";
}

// hooked set property
var_dump($rcH->newInstanceFromData(['a' => 1]));

// virtual property
var_dump($rcI->newInstanceFromData(['a' => 1, 'b' => 2]));

$instance = $rcI->newInstanceFromData(['a' => 1]);
var_dump($instance);
var_dump($instance->b);
$instance->b = 3;
var_dump($instance->b);

?>
--EXPECTF--
Exception: Cannot assign string to property A::$a of type int
In constructor of class A
object(A)#%d (2) {
["a"]=>
int(123)
["b"]=>
string(4) "good"
}
object(B)#%d (2) {
["a"]=>
int(123)
["b"]=>
string(4) "good"
}

Deprecated: Creation of dynamic property C::$a is deprecated in %s on line %d

Deprecated: Creation of dynamic property C::$b is deprecated in %s on line %d
object(C)#%d (2) {
["a"]=>
int(123)
["b"]=>
string(4) "good"
}
object(C)#%d (0) {
}
object(D)#%d (2) {
["a"]=>
int(123)
["b"]=>
string(4) "good"
}
Exception: Too few arguments to function E::__construct(), 0 passed and exactly 2 expected
object(E)#%d (2) {
["a"]=>
int(456)
["b"]=>
string(3) "foo"
}
object(F)#%d (2) {
["a"]=>
int(123)
["b"]=>
string(4) "good"
}
Exception: Cannot modify readonly property G::$b
object(H)#%d (1) {
["a"]=>
int(2)
}
object(I)#%d (1) {
["a"]=>
int(1)
}
object(I)#%d (1) {
["a"]=>
int(1)
}
int(2)
int(3)
Loading
Loading