php / php/doc-en

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

Open
#1,717 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug Extension: standard Status: Needs Triage
Dominant language
XML
Stars
596
Forks
890
Avg merge
1d 15h
Merged PRs (30d)
55

Description

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"

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the PHP 8.1.8 example with array_walk and array_walk_recursive, then inspect the existing documentation for readonly properties and these array functions. Done means the relevant documentation explains why the read-only array triggers the error during walking, with an example or cross-reference covering both functions.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.