Page 1 of 1
Which is better, CONSTANTS or $_SESSION?
Posted: Mon May 02, 2005 10:55 pm
by mwphurst
Since my server has switched to register_globals off, I started to be more thorough on how I defined my variables. I started writing everything with super globals which was required and seemed to make better sense. I never heard much about constants until recently, and after doing some checking I began to wonder if I should be using more constants than say $_SESSION variables. It appears they are about the same, but the $_SESSION variable can be changed anytime, making it seem to be the more popular choice. Or should constants be used for variables that shouldn't change, for say like a language file?
All of what I know, I have taught myself, and these constants are new to me. I have read about them, but would now like some others opinions.
Posted: Mon May 02, 2005 11:07 pm
by hawleyjr
I like to use constants for many reasons. However, Sessions have their place also.
For instance.
I have a page config.php with the following constants:
Code: Select all
define('WEBMASTER_EMAIL','nobody@example.com');
define('WEBMASTER_FULL_NAME','Godzilla');
define('MAX_NUMBER_OF_LOGIN_ATTEMPTS',3);
I know that as long as I include the file config.php in any page those three values will return the same values.
Code: Select all
$subject = 'Too Many Login Attempts';
$body = 'Dear '.WEBMASTER_FULL_NAME.', xyz user tried '.MAX_NUMBER_OF_LOGIN_ATTEMPTS.' times to login.';
mail ( WEBMASTER_EMAIL, $subject, $body );
Will always send an email to the webmaster. If the webmaster changes there is only one place where I have to change the email address.
Posted: Tue May 03, 2005 12:11 am
by magicrobotmonkey
Constants and $_SESSION variables aren't really the same at all. Constants can be intialized but once and should be used for static settings, as in the above example. They help make code more readable by cutting down on magic numbers/strings.
Variables in $_SESSION are simply variables that are persistant from page to page. They should definitely NOT be used for static settings, as they could be changed either accidentaly or intentionally.
Posted: Tue May 03, 2005 2:45 pm
by Ambush Commander
Look, putting globals everywhere is a recipe for disaster. Rethink the structure of your script: could a Singleton help? What data is long-lived. What data is temporary? What needs to be accessed everywhere?
Posted: Tue May 03, 2005 3:01 pm
by shiznatix
i think constants are good for putting a name on some number like
Code: Select all
define('ADMIN', '1');
define('USER', '2');
if ($_SESSION['user_id'] == ADMIN)
{
echo 'your so cool it hurts';
}
but i like to store stuff like the username and the user id as a session that way i can bring that from page to page without any extra code or includes