php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #37538 toString in sprintf/printf and %d modifier does't work as expected
Submitted: 2006-05-21 05:40 UTC Modified: 2006-05-21 09:23 UTC
From: mfischer@php.net Assigned:
Status: Not a bug Package: Strings related
PHP Version: * OS: *
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: mfischer@php.net
New email:
PHP Version: OS:

 

 [2006-05-21 05:40 UTC] mfischer@php.net
Description:
------------
The modifier %d doesn't work as one would expect sprintf/printf. When a string is returned, it is always replaced %d with '1' instead of the evaluated number of the __toString() output.

Consider this:

printf("%s %d", "4", "4");

will output "4 4", however if the parameters are replaced with an object whith magic __toString() which returns "4", %d is not replaced with 4 but with 1. It always returned 1, no matter what __toString() returns.



Reproduce code:
---------------
    class foo {
        function __toString() {
            return "4";
        }
    }
    printf("%s %d\n", new foo, new foo);
    printf("%s %d\n", "4", "4");


Expected result:
----------------
4 4
4 4


Actual result:
--------------
4 1
4 4


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-05-21 09:23 UTC] helly@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

%d is an integer conversion "(int)$obj" as apposed to a string conversion that is served by __toString().
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Oct 14 12:01:27 2024 UTC