Page 1 of 1

Get object name from within

Posted: Fri Jul 14, 2006 2:03 pm
by Ward
I don't know if this is possible, but I'm hoping it is. I'm trying to get an objects run-time variable name from within itself. For example, if I have this code:

Code: Select all

class foo
{
     public $firstName = "Billy";
     public $lastName = "Bob";
     
     function __construct()
     {
          // how can i get the variable name 'myFooInstance' from here?
     }
}

$myFooInstance = new foo();
The only solution I can think of is to pass each class it's unique variable name, like this:

Code: Select all

$myFooInstance = new foo('myFooInstance');

Posted: Fri Jul 14, 2006 2:21 pm
by dull1554
i don't know if it spossiable, but out of curiosity why do you want to do this? and if your working in your class why cant you reefer to it as $this?

Posted: Fri Jul 14, 2006 2:41 pm
by Ward
I'm trying to create loadViewState() and saveViewState() methods that would apply to every object. These would actually be called in each objects __construct() and __destruct() methods. However, I need each instance of an object to have a unique ID for this to work. I was hoping to make it automatic, but I may have to manually assign each object a unique ID.

Posted: Fri Jul 14, 2006 3:38 pm
by Ollie Saunders
its possible, using debug backtrace.
possible doesn't mean sensible though.

stick with the string in the constructor there is nothing wrong with that or if you want to create an internal id that the user of the class is unaware of use a static property like this:

Code: Select all

class Foo 
{
    private static $instanceIndex = 0;
    private $id;
    public function __construct()
    {
        $this->id = self::$instanceIndex++;
    }
    public function getId()
    {
        return $this->id;
    }
}

$a = new Foo();
$b = new Foo();
$c = new Foo();

echo $a->getId(); // 0
echo $c->getId(); // 2

Posted: Fri Jul 14, 2006 6:33 pm
by Chris Corbyn
ole wrote:or if you want to create an internal id that the user of the class is unaware of use a static property like this:

Code: Select all

class Foo 
{
    private static $instanceIndex = 0;
    private $id;
    public function __construct()
    {
        $this->id = self::$instanceIndex++;
    }
    public function getId()
    {
        return $this->id;
    }
}

$a = new Foo();
$b = new Foo();
$c = new Foo();

echo $a->getId(); // 0
echo $c->getId(); // 2
Ha! That's genius! Not sure where I'd ever need to use that though :)

Posted: Sat Jul 15, 2006 4:32 am
by Ollie Saunders
I found a use for it the other day. I'm writing a form management package and I wanted to generate ids attribute for all the fields, this was perfect.
I ditched it in the end in favor of forcing the user of the package to specify their own

Posted: Sat Jul 15, 2006 9:00 am
by feyd
A thread on this from a few days ago: viewtopic.php?t=51311