In PHP, the http_build_query function generates a URL-encoded query string from an array. The function also accepts an object, in which case its properties are treated as array elements. Objects which appear as values inside the array are handled the same way.
Since PHP 8.6, passing an object to http_build_query is deprecated, and objects found as values within the array are deprecated as well. Treating objects as arrays has been a source of confusion, in particular for objects which implement Stringable, because such objects are expected to be converted to a string instead.
Filter.php
<?php
class Filter
{
public function __construct(public string $category, public int $page)
{
}
}
<?php
require_once 'Filter.php';
$filter = new Filter('books', 2);
echo http_build_query($filter).PHP_EOL;
echo http_build_query(['filter' => $filter]).PHP_EOL;
Output:
Deprecated: http_build_query(): Passing an object for argument #1 $data to http_build_query() is deprecated, call get_object_vars() first instead in main.php on line 7
category=books&page=2
Deprecated: http_build_query(): object values within argument #1 $data to http_build_query() being interpreted as arrays is deprecated, instead the $data argument should be preprocessed with get_object_vars() in main.php on line 8
filter%5Bcategory%5D=books&filter%5Bpage%5D=2
The first deprecation refers to the object passed as the $data argument, while the second one refers to the Filter object found as a value inside the array. Both are separate deprecations with separate messages.
The example can be fixed by converting the object to an array with get_object_vars before the call:
<?php
require_once 'Filter.php';
$filter = new Filter('books', 2);
echo http_build_query(get_object_vars($filter)).PHP_EOL;
echo http_build_query(['filter' => get_object_vars($filter)]).PHP_EOL;
The generated query strings are identical. The get_object_vars function is not recursive, so an object stored inside another object has to be converted as well, otherwise the second deprecation is still raised.
Leave a Comment
Cancel reply