note 89872 modified in language.variables.scope by danbrown

From: Date: Thu, 26 Mar 2009 18:32:29 +0000
Subject: note 89872 modified in language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-152484@lists.php.net to get a copy of this message
External variables in a function I needed to access dynamically-created variables from an included file within a helper function. Because the list of $path_* variables I needed to access from the other file is itself dynamic, I didn't want to have to declare all possible variables within the function, and I was concerned at the overhead of declaring =all= members of $GLOBALS[] as global. However the following code worked for me: <?php function makePath($root, $atom) { $pos = strrpos($atom, '/'); if ($pos === false) { global ${'path_'.$atom}; $path = ${'path_'.$atom}; } else { global ${'path_'.substr($atom, 0, $pos)}; $path = ${'path_'.substr($atom, 0, $pos)}; } if ($path) return ($pos === false) ? $root.$path : $root.$path.substr($atom, $pos + 1); else return NULL; } ?> Regards, ::Leigh http://www.else.co.nz/ --was-- External variables in a function I needed to access dynamically-created variables from an included file within a helper function. Because the list of $path_* variables I needed to access from the other file is itself dynamic, I didn't want to have to declare all possible variables within the function, and I was concerned at the overhead of declaring =all= members of $GLOBALS[] as global. However the following code worked for me: function makePath($root, $atom) { $pos = strrpos($atom, '/'); if ($pos === false) { global ${'path_'.$atom}; $path = ${'path_'.$atom}; } else { global ${'path_'.substr($atom, 0, $pos)}; $path = ${'path_'.substr($atom, 0, $pos)}; } if ($path) return ($pos === false) ? $root.$path : $root.$path.substr($atom, $pos + 1); else return NULL; } Regards, ::Leigh http://www.else.co.nz/ http://php.net/manual/en/language.variables.scope.php

« previous php.notes (#152484) next »