note 72392 deleted from function.print-r by googleguy

From: Date: Tue, 22 Oct 2013 15:00:08 +0000
Subject: note 72392 deleted from function.print-r by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-197289@lists.php.net to get a copy of this message
Note Submitter: markus (at) maxxmaster (d0t) org ---- Explanation: The problem with figuring out what value is what key in that variables scope is that several variables might have the same value. To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match. Then we loop through the scope ( semi recursively ) the variable is contained in and when there is a match of our modified value, we can grab the correct key and output the name. Bugs: You can see in the 5th Example, that the so-called non-existant variable infact exists ;|, the problem with referenced variables (as used in the my_r function) is, that they have to exist at call-time to reference them. that is why my_r("test") will result in a fatal error. if you have ideas to solve that, don't hesitate to mention them. Examples: 1. Use of a variable contained in the global scope (default): <?php $my_global_variable = array("nice", "try", "guybrush"); my_r($my_global_variable); /* Outputs: $my_global_variable: Array ( [0] => nice [1] => try [2] => guybrush ) */ ?> 2. Use of a local variable (in a function): <?php function my_local_function() { $my_local_variable = array("nice", "try", "guybrush"); my_r($my_local_variable,get_defined_vars()); } my_local_function(); /* Outputs: $my_local_variable: Array ( [0] => nice [1] => try [2] => guybrush ) */ ?> 3. Use of an object property: <?php class myclass{ public function __constructor(){ // depending on php version ;) $this->my_object_property = array("nice", "try", name => array("guybrush")); } public function myclass(){ // depending on php version ;) $this->my_object_property = array("nice", "try", name => array("guybrush")); } } $obj = new myclass; my_r($obj->my_object_property); /* Outputs: $obj->my_object_property: Array ( [0] => nice [1] => try [name] => Array ( [0] => guybrush ) ) */ ?> 4. Use of a sub-array and an additional label <?php $foo=array("nice","try",name => array("guybrush","threapwood")) my_r($foo["name"],"position 1"); /* Outputs: $foo["name"] #position 1# Array ( [0] => guybrush [1] => threapwood ) */ ?> 5. Use of non existant Variables (standard-behaviour of print_r) <?php my_r($foo=array("nice","try","guybrush")); /* Outputs: Array ( [0] => nice [1] => try [2] => guybrush ) */ ?>

« previous php.notes (#197289) next »