#586·prophecy

Mocking PHP 8.2 readonly classes generates readonly double with untyped property and fails

Author: vuryssCreated Jan 25, 2023Updated Nov 14, 2024
LabelsPHP8.2

When creating a double of a readonly class I ger the following error:

PHP Fatal error: Readonly property Double\Path\To\ClassName\P1::$objectProphecyClosure must have type in /var/www/html/vendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCreator.php(49) : eval()'d code on line 3

This comes from eval of the generated code likes this:

namespace Double\Path\To\ClassName {
    readonly class P1 extends \Path\To\ClassName implements \Prophecy\Prophecy\ProphecySubjectInterface, \Prophecy\Doubler\Generator\ReflectionInterface {
        private $objectProphecyClosure;

        public  function __construct(...

Readonly classes make all class properties readonly. And readonly properties must have a type. So this generated property objectProphecyClosure fails that.

It's generated in ProphecySubjectPatch::apply

May be the double class doesn't need to be readonly or we can make the generated fields typed?