Page 1 of 1
Dynamically Generated Static Vars
Posted: Fri Nov 06, 2009 3:21 pm
by JNettles
I need to dynamically generate a list of static variables in a function.
Example.
Code: Select all
<?php
function generateVars()
{
$list = array("Crops", "Cattle", "Staff");
foreach($list as $var)
{
STATIC ${$var}; ?????????
}
}
This seems like it should be simple and I'm sure it is - what is the syntax for looping through and dynamically declaring those static variables? Thanks.
Re: Dynamically Generated Static Vars
Posted: Fri Nov 06, 2009 3:29 pm
by flying_circus
Isn't the static keyword reserved for methods/variables inside of classes only? I guess I've never tried it outside of a class.
Re: Dynamically Generated Static Vars
Posted: Fri Nov 06, 2009 3:48 pm
by VladSun
Why would you need this?
Re: Dynamically Generated Static Vars
Posted: Fri Nov 06, 2009 11:18 pm
by JNettles
You can declare a static variable inside of a function. I'm using it to make a reference to a class.
Re: Dynamically Generated Static Vars
Posted: Sat Nov 07, 2009 3:40 am
by josh
You should consider rethinking your approach. e.g. why do they have to be static? why not a regular array?
Re: Dynamically Generated Static Vars
Posted: Sat Nov 07, 2009 7:22 am
by Weirdan
you can't create static variables using variable variables, but you can use single static array instead, like this:
Code: Select all
function generateVars()
{
static $vars = array();
if (something()) $vars['Cattle'] = 1;
if (somethingElse()) $vars['Staff'] = 2;
//...
}
Re: Dynamically Generated Static Vars
Posted: Mon Nov 09, 2009 1:36 pm
by JNettles
Thanks. I think the array concept will work.