From 029cb118b26c0146a7622809170d190b8b05f789 Mon Sep 17 00:00:00 2001 From: ndossche <7771979+ndossche@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:11:48 +0100 Subject: [PATCH] ext/reflection: Don't call destructor when constructor is not public in newInstance(Args)() Normally, an object whose ctor failed would never run its dtor, but for reflection it did when the ctor was not public. To solve this we mark the object as ctor-failed. --- ext/reflection/php_reflection.c | 2 ++ .../newInstance_nonpublic_ctor_no_dtor.phpt | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 ext/reflection/tests/newInstance_nonpublic_ctor_no_dtor.phpt diff --git a/ext/reflection/php_reflection.c b/ext/reflection/php_reflection.c index 1e1387177b37..354888a6fb4c 100644 --- a/ext/reflection/php_reflection.c +++ b/ext/reflection/php_reflection.c @@ -5267,6 +5267,7 @@ ZEND_METHOD(ReflectionClass, newInstance) 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)); + zend_object_store_ctor_failed(Z_OBJ_P(return_value)); zval_ptr_dtor(return_value); RETURN_NULL(); } @@ -5342,6 +5343,7 @@ ZEND_METHOD(ReflectionClass, newInstanceArgs) 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)); + zend_object_store_ctor_failed(Z_OBJ_P(return_value)); zval_ptr_dtor(return_value); RETURN_NULL(); } diff --git a/ext/reflection/tests/newInstance_nonpublic_ctor_no_dtor.phpt b/ext/reflection/tests/newInstance_nonpublic_ctor_no_dtor.phpt new file mode 100644 index 000000000000..43940d8dea0a --- /dev/null +++ b/ext/reflection/tests/newInstance_nonpublic_ctor_no_dtor.phpt @@ -0,0 +1,29 @@ +--TEST-- +ReflectionClass::newInstance(Args)() must not call the destructor when the constructor is not public +--FILE-- +newInstance(); +} catch (Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} +try { + $rc->newInstanceArgs(); +} catch (Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} + +?> +--EXPECT-- +ReflectionException: Access to non-public constructor of class A +ReflectionException: Access to non-public constructor of class A