Skip to content

Commit f72c603

Browse files
0xRashadjordikroon
andauthored
Clarify http_build_query() behavior with objects and __toString() (#5529)
* Clarify http_build_query() behavior with objects and __toString() Addresses legacy bug 66966 by adding a note and an example demonstrating the need for explicit string casting. https://bugs.php.net/bug.php?id=66966 Co-authored-by: Jordi Kroon <jordikroon@me.com>
1 parent 963af75 commit f72c603

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

reference/url/functions/http-build-query.xml

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@
4040
If <parameter>data</parameter> is an object, then only public
4141
properties will be incorporated into the result.
4242
</para>
43+
<note>
44+
<simpara>
45+
The <link linkend="object.tostring">__toString()</link> magic method is
46+
not called when an object is evaluated. To use the string representation of an
47+
object in the query string, the object must be explicitly cast to a string.
48+
</simpara>
49+
</note>
4350
</listitem>
4451
</varlistentry>
4552
<varlistentry>
@@ -260,6 +267,44 @@ echo http_build_query($parent);
260267
<screen>
261268
<![CDATA[
262269
pub=publicParent&pub_bar%5Bpub%5D=publicChild
270+
]]>
271+
</screen>
272+
</example>
273+
274+
<example>
275+
<title>Using <function>http_build_query</function> with objects containing
276+
<link linkend="object.tostring">__toString()</link>
277+
</title>
278+
<programlisting role="php">
279+
<![CDATA[
280+
<?php
281+
class Foo {
282+
public $publicProperty = 'visible';
283+
284+
public function __toString() {
285+
return "bar";
286+
}
287+
}
288+
289+
$params = array(
290+
'a' => 'b',
291+
'foo' => new Foo()
292+
);
293+
294+
// Without casting, http_build_query reads the public properties
295+
echo http_build_query($params) . "\n";
296+
297+
// With explicit casting, http_build_query uses the __toString() output
298+
$params['foo'] = (string) new Foo();
299+
echo http_build_query($params) . "\n";
300+
?>
301+
]]>
302+
</programlisting>
303+
&example.outputs;
304+
<screen>
305+
<![CDATA[
306+
a=b&foo%5BpublicProperty%5D=visible
307+
a=b&foo=bar
263308
]]>
264309
</screen>
265310
</example>

0 commit comments

Comments
 (0)