Skip to content

array_walk and (_recursive) cause an error if applied to readonly properties #1717

Open
@SpiGAndromeda

Description

@SpiGAndromeda

Description

The following code should check if the passed array of variables contains any elements that are objects. If that is so, an exception is thrown:

<?php
declare(strict_types=1);

final class Variables
{
    /**
     * @param array<string, mixed> $variables
     */
    public function __construct(private readonly array $variables)
    {
        $objectVariables = [];
        array_walk_recursive($this->variables, static function(mixed $variable) use (&$objectVariables) {
            if (is_object($variable)) {
                $objectVariables[] = $variable;
            }
        });

        if (0 !== count($objectVariables)) {
            throw VariablesContainObjectsException::create();
        }
    }

    /**
     * @return array<string, mixed>
     */
    public function get(): array
    {
        return $this->variables;
    }
}

An Error is thrown at the 'array_walk_recursive' call: Cannot modify readonly property Variables::$variables. The trace provides no additional information. (I also tested it with 'array_walk' with the same result)

As far as I understood, walking through an array without modifiying anything should not cause an error, because no value is manipulated. If that behavior is correct, it should be documented somewhere. I found no information about such behavior of readonly properties in array methods.

PHP Version

PHP 8.1.8

Operating System

PHP 8.1 docker image "php:8.1-apache"

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions