PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
JNettles
Forum Contributor
Posts: 228 Joined: Mon Oct 05, 2009 4:09 pm
Post
by JNettles » Fri Nov 06, 2009 3:21 pm
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.
flying_circus
Forum Regular
Posts: 732 Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR
Post
by flying_circus » Fri Nov 06, 2009 3:29 pm
Isn't the static keyword reserved for methods/variables inside of classes only? I guess I've never tried it outside of a class.
VladSun
DevNet Master
Posts: 4313 Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria
Post
by VladSun » Fri Nov 06, 2009 3:48 pm
Why would you need this?
There are 10 types of people in this world, those who understand binary and those who don't
JNettles
Forum Contributor
Posts: 228 Joined: Mon Oct 05, 2009 4:09 pm
Post
by JNettles » Fri Nov 06, 2009 11:18 pm
You can declare a static variable inside of a function. I'm using it to make a reference to a class.
josh
DevNet Master
Posts: 4872 Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida
Post
by josh » Sat Nov 07, 2009 3:40 am
You should consider rethinking your approach. e.g. why do they have to be static? why not a regular array?
Weirdan
Moderator
Posts: 5978 Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine
Post
by Weirdan » Sat Nov 07, 2009 7:22 am
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;
//...
}
JNettles
Forum Contributor
Posts: 228 Joined: Mon Oct 05, 2009 4:09 pm
Post
by JNettles » Mon Nov 09, 2009 1:36 pm
Thanks. I think the array concept will work.