El código de abajo tiene una calidad que promueve la eficiencia de almacenamiento en caché:
class Object {
public $instance_variable;
public $last_added_global_variable;
public function __construct(){
//we are saving the global variable before this one so that
//we can be confident that we will always get the correct value
$this->last_added_global_variable = $this->get_last_variable_added()[count($array_of_global_variables)-1];
}
//runs everytime a function is called in this class
public function __call(){
//remember, this is skipped whenever the variable name is saved
if(!$this->instance_variable){
for($i=0; $i=count($this->get_last_variable_added()); $i++){
if($this->last_added_global_variable == get_last_variable_added()[$i]){
$this->instance_variable = get_last_variable_added()[$i+1];
}
}
}
}
private function get_last_variable_added(){
$array_of_global_variables = array();
foreach($GLOBALS as $g=>$v){
array_push($array_of_global_variables, $g);
}
//return last added global variable
return $array_of_global_variables;
}
}
Aunque aparece costosa, es insignificante.
Puede notar que encontrar la última variable añadida a través de un bucle de variable global es imposible mientras todavía está en la función de construcción.
No hay una forma mágica de encontrar un objeto, conociendo solo su clase. Tendrás que poner tu instancia en algún lugar donde puedas encontrarla más tarde. –
Con al menos ocho respuestas y Singleton, Registry y instanceof, etc. todos mencionados, es posible que desee ser más preciso acerca de lo que está tratando de hacer. – Gordon