I am working on a app at the moment, as practice mostly. But I have like 25 $vars that accumulate over the course of like 2 pages of forms gathering information. On the final page i use all these $vars to put together an estimate. My question is:
Is there a "common best practice" for handling them? like right now i just have a great big list at top of my pages. Should i use an includes file for $vars? Or use sessions to carry them all around until i am ready to pull them all in for my calculations on the final page?

Recommended Answers

All 2 Replies

I don't think there is really a best practice for handling variables. It really depends on the scope requirements of the variables.

If you prefer to work with many individual variables than continue to use $var1, $var2, etc etc.
If you don't like having so many loose variables, you could create a single array (single or multiple dimensions) that contains all the values.



$variable = array(
  'page' => array(
    'title' => 'Page Title',
    'width' => 960,
  'form' => array(
    'field1' => 'value',
    'field2' => 37,
    'field3' => true,

If you use the array you can access everything down using: echo $variable['page']['title']; You also could slug all the variables into an object if you prefer the object notation of object->variable;

$obj = new stdClass();
$obj->page = new stdClass();
$obj->page->title = 'Page Title';
$obj->page->width = 960;

Personally I don't see much value in using objects as just empty stores like that.

Beyond the way you use the variables, you have to consider persistence. $var = 4; is only available within its local scope and must be passed into functions/objects etc. This is also only persisted for the current request.

Sessions allow you to persist volatile data over multiple requests while the use maintains their session. $_SESSION['var'] = 4; => index.php => go.php => xyz.php echo $_SESSION['var']; //4 Sessions are also global and can be accessed anywhere at anytime. But if the user loses their association with the session or closes the browser the variable will not exist.

The last thing you can do is persist the data in some kind of storage, sql database, flat file, nosql database etc. You can than store and retrieve this data as necessary. Essentially though while you're working with data your retrieve from a database you would be using some combination of the above.

commented: Very helpful, and knowledgable! +2

Thank you. Great advise.. i hadn't thought of all that. Thanks again, very helpful! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.