note 92747 rejected from language.variables by rbowen
| From: | rbowen@php.net | Date: | Tue, 06 Apr 2010 17:15:17 +0000 |
| Subject: | note 92747 rejected from language.variables by rbowen | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-167734@lists.php.net to get a copy of this message | ||
Note Submitter: the_good_technician [a.t.] y-a-h-o-o.
----
Sometimes it's necessary to retrieve the value of $this from within an object.
This solution dedicates a public var $ID to store a unique identifier for the object:
<?php
class Someclass {
public $ID;
public function what_is_this() {
return '$this is: ' . $this->get_varname();
}
private function get_varname() {
$this->ID = uniqid();
foreach($GLOBALS as $key => $val) {
if (is_a($val,'Someclass')) {
if ($val->ID === $this->ID) {
return $key;
break;
}
}
}
}
}
// example:
$my_var_instance = new Someclass;
echo $my_var_instance->what_is_this(); // returns '$this is: my_var_instance'
?>