note 38973 deleted from functions by nlopess
| From: | nlopess@php.net | Date: | Wed, 14 Jan 2004 19:11:59 +0000 |
| Subject: | note 38973 deleted from functions by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-63556@lists.php.net to get a copy of this message | ||
Note Submitter: Diego Vilar, at Unimed Sergipe, Brazil
----
I came across the problem so discussed in this thread.. and after reading some people's
sugestions and ideas, I found that using globals is the way. In my case, I had a function B inside
another function A, and this function B needed access to variables defined inside A. But I wanted to
reference those variables, inside both functions, as local variables, Thats how I solved in an
elegant way, I think..
function Alpha() {
function Beta() {
// DEFINITIONS
global $Apple, $Orange;
// Do whatever u want with $Apple and $Orange
...
}
// DEFINITIONS
$Banana = "";
$Apple = "";
$Orange = "";
// Export local variables needed outside
$GLOBALS["Apple"] = &$Apple;
$GLOBALS["Orange"] = &$Orange;
// Do some stuff inside A with its variables
$Apple = "red, juicy";
$Orange = "orange, also juicy";
Beta();
}
Now, you realize that this is not new, but the center idea here is to separete a block inside the
function to "export" whatever variables you need to give access to other functions,
keeping its names, thus making the code more readable and organized.
For those who need to call Alpha() more then once, it would be useful to encolse Beta() definition
inside a condition that checks if it's already been declared, just like bellow:
...
if (!function_exists("Beta")) {
function Beta() {
// DEFINITIONS
global $Apple, $Orange;
// Do whatever u want with $Apple and $Orange
...
}
}
...
Now, for those who want a more professional solution, I'd sugest creating a function that
registers local and global variables. That way, you could declare a variable by doing somthing like
DefLocalGlobal("varname"), and the DefLocalGlobal() function would, using eval(), declare
the local instance ($varname) and its global reference ($GLOBAL["varname"]). You could
even write a function for garbage collect those variables just before leaving the caller function,
so you would free memory when those variables would not be necessary anymore.