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.
Which is better, CONSTANTS or $_SESSION?
Moderator: General Moderators
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:
I know that as long as I include the file config.php in any page those three values will return the same values.
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.
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);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 );-
magicrobotmonkey
- Forum Regular
- Posts: 888
- Joined: Sun Mar 21, 2004 1:09 pm
- Location: Cambridge, MA
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.
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.
- Ambush Commander
- DevNet Master
- Posts: 3698
- Joined: Mon Oct 25, 2004 9:29 pm
- Location: New Jersey, US
- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
i think constants are good for putting a name on some number like
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
Code: Select all
define('ADMIN', '1');
define('USER', '2');
if ($_SESSION['user_id'] == ADMIN)
{
echo 'your so cool it hurts';
}