Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store global variables

Tags:

php

mysql

I'm writing an application in PHP that uses a LOT of global variables that are used throughout the script. Right now, I have a config file that stores a bunch of global variables created by using the define() function, but since I'm going to have so many, would it be better to create a table in the database that is just contains variable names and values, and to access these have a function which queries the database, finds the variable, returns the value, and caches the value for future use.

I'm also welcome to other ideas for storing global variables.

like image 946
Steve Gattuso Avatar asked Jan 13 '09 20:01

Steve Gattuso


2 Answers

The define() function creates constants, not global variables. Global variables should be used sparingly as they can be corrupted accidentally (or maliciously!), however constants are perfectly safe.

I find it easiest to just have a file named 'config.php' which sets up all the constants, it's faster and simpler.

like image 151
too much php Avatar answered Sep 19 '22 01:09

too much php


Well, this depends on the structure of your application. If in a given page-load you'll only really need one or two of several hundred variables, then benchmark testing might show that querying the database might be quicker than including a massive configuration file. However, you'll need to be wary of bogging down your database with too many queries every time the user wants to do anything. Caching can cut down on the overhead added by redundant requests, but that's the extent of its use.

If these variables are mostly short strings or boolean flags, I think that your answer will largely rest on what you'll be able to maintain well. A well-structured .ini file would be easier to maintain than a big database if those variables rarely change and are always changed by hand. If these variables are changing constantly and never by hand, you'd probably be smarter to just load all of the variables into a database.

Personally, I've found myself in both situations and I've used both methods accordingly. If you're really indecisive, you can always just do some benchmark tests. Time a page load that pulls config information from the database, then time a page load using a .ini file (or a .php file full of define()s).

(And pedantically speaking, define() creates constants in the global scope, not global variables.)

like image 43
Phantom Watson Avatar answered Sep 21 '22 01:09

Phantom Watson