Dynamically Generated Static Vars

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

Post Reply
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Dynamically Generated Static Vars

Post 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.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Dynamically Generated Static Vars

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Dynamically Generated Static Vars

Post by VladSun »

Why would you need this?
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Re: Dynamically Generated Static Vars

Post by JNettles »

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

Re: Dynamically Generated Static Vars

Post by josh »

You should consider rethinking your approach. e.g. why do they have to be static? why not a regular array?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Dynamically Generated Static Vars

Post 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;
       //...
}
 
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Re: Dynamically Generated Static Vars

Post by JNettles »

Thanks. I think the array concept will work.
Post Reply