PHP - Accessing object name within a class function

First question here. Please excuse noob errors.

I want to be able to refer to an object name within a function.

Let's imagine the function within a class is display_report(). I call the function for the object $jan2011 by using the code:


Once inside the display_report() function, I can refer to object variables as $this->date or $this->title, where $date and $title are both variables within the class.

But how can I determine within the display_report() function that the object it's been called with is $jan2011? Just using $this doesn't seem to be permissible.

What I'm trying to do is create a variable something like this:

$name = "W_".$this."_7";

I would hope that $name would be set to W_jan2011_7 (or maybe, W_$jan2011_7) but it doesn't work.

Any help would be appreciated! Thanks.

-------------Problems Reply------------

You can't access the reference name from the inside of an object, they are two completely different contexts. The approach that you are taking is not OO-compliant, try instead to put an attribute (e.g. "name") in the report class and override the __toString method to output the string representation of the object (more infos about __toString are in php docs).

In general, you can't; there are situations where the variable won't even have a name. Imagine:

function foo()
return new Report();


I would suggest adding a name field to your class.

Category:php Views:0 Time:2011-11-30

Related post

Copyright (C), All Rights Reserved.

processed in 0.129 (s). 11 q(s)