php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #30098 Cannot use __toString on $this
Submitted: 2004-09-15 20:18 UTC Modified: 2004-09-17 09:13 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: brandon at osuosl dot org Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.0.1 OS: *
Private report: No CVE-ID: None
 [2004-09-15 20:18 UTC] brandon at osuosl dot org
Description:
------------
The automatic __toString method does not work on $this. 

I don't know if it should or not but it seems like it should be ok to do this. 

Thanks.

http://dev2.osuosl.org/~philips/tostring/index.php
http://dev2.osuosl.org/~philips/tostring/index.phps

Reproduce code:
---------------
class Foo {
   function __toString() {
       return "What ever";
   }
    
    function ihatemylife() {
        $str = (string) $this;
        return $str;
 }
}

$obj = new Foo;

$str = (string) $obj; // call __toString()

echo $obj; // call __toString()

echo "<br />";

echo $obj->ihatemylife();

echo "<br />";

phpinfo();

Expected result:
----------------
This line should return "What ever" 
echo $obj->ihatemylife();

Actual result:
--------------
Object id #1

Patches

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-09-15 20:32 UTC] robertd at onid dot orst dot edu
Not sure if this is needed information, but:
the automatic __toString will also fail on member objects of $this.  For example:
-------------------------
$class = new MyClass();
echo $class->something();

class MyClass {
    private $obj;

    public function something() {
        $this->obj = new SomeObject();
        $str = (string) $this->obj;
        return $str;
    }
}

class SomeObject {
    public function __toString() {
        $str = 'Some string';
        return $str;
    }
}
-------------------------

Echoes "Object id #2"
 [2004-09-17 00:34 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

__toString() is never called automatically.

We had to drop this magic right before 5.0 was released and may be able to reintroduce it to 5.1.
 [2004-09-17 00:53 UTC] helly@php.net
Erm never besides direct 'print $obj' or 'echo $obj' of course.
 [2004-09-17 00:56 UTC] brandon at osuosl dot org
How does 'print $obj' or 'echo $obj' vary from 'print $this' or 'echo $this' ?  Shouldn't they all behave the same?
 [2004-09-17 09:13 UTC] helly@php.net
You used conversion: 
$str = (string) $obj; 
echo (string) $obj;
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Aug 14 19:01:27 2024 UTC