php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #29787 Object instance variables not visible from within __toString()
Submitted: 2004-08-22 14:56 UTC Modified: 2004-08-23 10:25 UTC
From: adamgoossens at users dot sourceforge dot net Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.0.1 OS: Windows XP Professional, SP2
Private report: No CVE-ID: None
 [2004-08-22 14:56 UTC] adamgoossens at users dot sourceforge dot net
Description:
------------
Hi folks,

When overriding __toString() to provide custom object to string conversion it appears as though object level variables are not visible from within the function.

This affects public, private and protected variables equally. Static member variables and class constants are not affected.

Reproduce code:
---------------
class Foo
{
	public $_myVar;
	public static $_static = 'I am static.';
	const MY_CONST = 'I am constant.';

	function __construct()
	{
		$_myVar = 'A public variable.';

	}

	function __toString()
	{
		return "Variables:\n".$this->_myVar."\n".Foo::$_static."\n".Foo::MY_CONST;
	}
}

$foo = new Foo;
echo $foo;

Expected result:
----------------
Variables:
A public variable.
I am static.
I am constant.

Actual result:
--------------
Variables:
I am static.
I am constant.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-08-22 17:52 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

You didn\'t set the public var so its value is NULL.
 [2004-08-23 10:25 UTC] adamgoossens at users dot sourceforge dot net
Oops. And I thought I had been so careful and checked everything. :)

Apologies for wasting your time.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Dec 02 14:00:01 2025 UTC