Skip to content

PHP 8.0: array_walk(): Argument $key must be passed by reference, value given #1085

@sebsel

Description

@sebsel

While waiting on a reply on #1084, I'm stuck in a situation where I do have PHP 8.0 on my machine already, but cannot update my project because I cannot do a composer install on PHP 8.0. I can however run my already locally installed code in PHP 8.0, so there I got this bug.

Summary of problem or feature request

I got the following Exception when running stuff with Elastic in PHP 8.0:

 ErrorException

  Elasticsearch\Connections\Connection::Elasticsearch\Connections\{closure}(): Argument #2 ($key) must be passed by reference, value given

  at vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php:357
    353▕                         $value = 'true';
    354▕                     } elseif ($value === false) {
    355▕                         $value = 'false';
    356▕                     }
  ➜ 357▕                 }
    358▕             );
    359▕
    360▕             $uri .= '?' . http_build_query($params);
    361▕         }

Code snippet of problem

The full method where this happens is here (comment mine):

    private function getURI(string $uri, ?array $params): string
    {
        if (isset($params) === true && !empty($params)) {
            array_walk(
                $params,
## line 346:
                function (&$value, &$key) {
                    if ($value === true) {
                        $value = 'true';
                    } elseif ($value === false) {
                        $value = 'false';
                    }
                }
            );

            $uri .= '?' . http_build_query($params);
        }

        if ($this->path !== null) {
            $uri = $this->path . $uri;
        }

        return $uri ?? '';
    }

The solution is as simple as just removing the & before $key on line 346, or removing &$key all together (it's unused).

Note that the documentation on https://www.php.net/array_walk says:

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

... so I think that's why in PHP 8.0 this got stricter?

System details

  • Operating System: macOS 10.15.7
  • PHP Version: v8.0.0
  • ES-PHP client version: v7.9.1
  • Elasticsearch version: v7.6.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions