Connecting Tech Pros Worldwide Forums | Help | Site Map

Retrieving the name of the variable that holds the instance

Member
 
Join Date: Jul 2006
Posts: 92
#1: Mar 21 '08
Consider the following codes:

[PHP]class x
{

function get_instance_var_name(){

#HOW DO I GET THE NAME OF THE CURRENT INSTANCE???

return($instance_name)

}

}

$santas_red_underpants = new x;
print $santas_red_underpants -> get_instance_var_name();
[/PHP]

How do I get get_instance_name() to find the name of the current instance, which is santas_red_underpants

Member
 
Join Date: Nov 2007
Location: Russia, Saint-Petersburg
Posts: 82
#2: Mar 21 '08

re: Retrieving the name of the variable that holds the instance


It is impossible in the way you have describe it.
You should pass instance name manually, something like that :
[PHP]class x {
private $instanceName;
public function __construct($instanceName) {
this->instanceName = $instanceName;
}
}

$santas_red_underpants = new x('santas_red_underpants');[/PHP]

Anyway, why do you need to know instance name? Explain your problem. Maybe together we could find better solution.

Regards.
Member
 
Join Date: Jul 2006
Posts: 92
#3: Mar 22 '08

re: Retrieving the name of the variable that holds the instance


Great suggestion and very efficient too.

I am trying to create a core of a framework that uses a single instances of the required classes for all tasks. But the risidual data creates a problem for any new tasks and results in unwanted effects.

So now I'm thinking of storing unique data on a per-instance basis, while still using single instances of the required classes. That way I can keep the overheads to a minimum.

Also look at the following for retrieving variable that holds the instance. Its extremely resource hungry, especially if a lot of calls need to be made but its a start:

[PHP]
function instance_name(){

$instance = md5(serialize($this));

foreach($GLOBALS as $variable => $value){

if( md5(serialize($value)) == $instance ){

return $variable;
}
return(false);
}

}
[/PHP]
Member
 
Join Date: Nov 2007
Location: Russia, Saint-Petersburg
Posts: 82
#4: Mar 24 '08

re: Retrieving the name of the variable that holds the instance


Still haven't clear understanding of existing problem. Maybe you should use static objects if you want to have only one instance of class?
Are you sure your solution isn't reinventing of wheel?
Reply