Re: Good way to make variables global (?)
| From: | Peter Fraterdeus | Date: | Tue, 10 Oct 2000 01:40:14 +0000 |
| Subject: | Re: Good way to make variables global (?) | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-19281@lists.php.net to get a copy of this message | ||
Erica--
I sympathize ;-)
The problem turns up in passing values from HTML forms to functions or method calls...
The HTML form has fields named "customer_ID", "company", etc.
PHP will create globals from these with the name $customer_ID, $company, etc.
I've started using something like the below:
// all the field names in an array
$customer_fields= array (
'customer_ID',
'name_first',
'name_last',
'company',
'eMail',
...
'isReseller',
'isDistributor',
'date_created',
'date_last_update'
);
function getCustomerProfile($my_customer) { // retrieve customer data from database
// These are the HTML form variables, and have to be global
global $customer_fields;
reset ($customer_fields);
// this is the global field list defined above
while (list ($key,$value)=each ($customer_fields)) { // for each field
eval("global $".$value.";"); // this creates the global inside the function
} // it's very likely there's a different, better solution to this!
$UID=$eMail;
$my_customer->get_Profile($UID);
// copy the database record to the form global variables
reset ($customer_fields);
// this is the global field list defined above
while (list ($key,$value)=each ($customer_fields)) { // for each field
if (isset($my_customer->$value)) $$value=$my_customer->$value;
} // while
}
and of course, the fields have the same names as my SQL columns...
I expect there's a more elegant way to do this.
regards
Peter
At 5:32 PM -0700 10/9/00, Lars Torben Wilson wrote:
>Erica Douglass writes:
>> I recently stumbled upon a way to make all variables global. I did this
>> because I got sick of writing out global variable after global variable in
> > my functions.
>....
> >
>> My impression: This is a very cool snippet of code... as long as you
>> understand the implications.
>>
>> Erica
>
>Here's the first thing I notice: the above code extracts _all_
>elements of $GLOBALS, for _each_ element of $GLOBALS. In other words,
>extract() already extracts() all of the elements of the array it is
>given; you don't need to do it once for each element. So if your
>$GLOBALS array has, say, 20 elements, the above code is doing 20 times
>the work it needs to do. Try this:
>
>function example_function() {
> extract($GLOBALS);
> . . .
>}
...
--
AzByCx DwEvFu GtHsIr JqKpLo MnNmOl PkQjRi ShTgUf VeWdXc YbZa&@
Peter Fraterdeus http://www.midsummernightstamps.com
Magical Images from the Moon's Garden!
Type on the Edge of History; In Search of the Wild Photon, &c.
http://www.dezinecafe.com/fraterdeus
BookSense http://www.booksense.com
Independent local booksellers on the web.