[DOC-CVS] [doc-en] master: Clarify http_build_query() behavior with objects and __toString() (#5529)

[email protected] (Rashad Borbély via GitHub) Tue, 5 May 2026 15:07:21 +0000
Newsgroups php.doc.cvs
Message-ID <[email protected]>
Author: Rashad Borbély (0xRashad)
Committer: GitHub (web-flow)
Pusher: jordikroon
Date: 2026-05-05T17:07:18+02:00

Commit: https://github.com/php/doc-en/commit/f72c6031982a6f8152ef351d20f8e0d90e8f1612
Raw diff: https://github.com/php/doc-en/commit/f72c6031982a6f8152ef351d20f8e0d90e8f1612.diff

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 <[email protected]>

Changed paths:
  M  reference/url/functions/http-build-query.xml


Diff:

diff --git a/reference/url/functions/http-build-query.xml b/reference/url/functions/http-build-query.xml
index d1a5b63c826b..940812fbfd01 100644
--- a/reference/url/functions/http-build-query.xml
+++ b/reference/url/functions/http-build-query.xml
@@ -40,6 +40,13 @@
        If <parameter>data</parameter> is an object, then only public
        properties will be incorporated into the result.
       </para>
+      <note>
+       <simpara>
+        The <link linkend="object.tostring">__toString()</link> magic method is
+        not called when an object is evaluated. To use the string representation of an
+        object in the query string, the object must be explicitly cast to a string.
+       </simpara>
+      </note>
      </listitem>
     </varlistentry>
     <varlistentry>
@@ -260,6 +267,44 @@ echo http_build_query($parent);
    <screen>
 <![CDATA[
 pub=publicParent&pub_bar%5Bpub%5D=publicChild
+]]>
+   </screen>
+  </example>
+
+  <example>
+   <title>Using <function>http_build_query</function> with objects containing
+    <link linkend="object.tostring">__toString()</link>
+   </title>
+   <programlisting role="php">
+<![CDATA[
+<?php
+class Foo {
+    public $publicProperty = 'visible';
+
+    public function __toString() {
+        return "bar";
+    }
+}
+
+$params = array(
+    'a' => 'b',
+    'foo' => new Foo()
+);
+
+// Without casting, http_build_query reads the public properties
+echo http_build_query($params) . "\n";
+
+// With explicit casting, http_build_query uses the __toString() output
+$params['foo'] = (string) new Foo();
+echo http_build_query($params) . "\n";
+?>
+]]>
+   </programlisting>
+ &example.outputs;
+   <screen>
+<![CDATA[
+a=b&foo%5BpublicProperty%5D=visible
+a=b&foo=bar
 ]]>
    </screen>
   </example>