Jump to content

Constants Vs. Variables for Config Files?


Jessica

Recommended Posts

Is there any reason to use constants over variables when creating a config-type file?
For instance, I have a file which gets included on every page, which contains paths, settings, etc.
Is there any good reason they should be constants rather than variables? The only thing I can see is that "the scope of a constant is global", meaning if I want to use it in a function I don't have to use global $var;

Your thoughts? Which is better? Does one save time somehow, etc?
Link to comment
Share on other sites

Try this:

[code]
<?php

define('FOO', 'bar');
$foo = 'bar';


function someThirdPartyCode_BAD()
{
global $foo;

$foo = 'not-bar';

if($foo == 'bar'){
print "Program Works <br />";
}else{
print "Obscure Bug <br />";
}
}

function someThirdPartyCode_NOT_AS_BAD()
{
define('FOO', 'not-bar');

if(FOO == 'bar'){
print "Program Works <br />";
}else{
print "Obscure Bug <br />";
}
}

someThirdPartyCode_BAD();
someThirdPartyCode_NOT_AS_BAD();

?>

[/code]

I typically create a constants.php file and store all my constant definitions there.

Best,

Patrick
Link to comment
Share on other sites

You all said it already. As utexas_pjm code demonstrates, you can't change a constant once it has been defined (PHP will give a notice when the second define is attempted).

Global scope and not being able to change the value of a constant are the best advantages for their use. Using constants for filenames, paths and such is good because outside hacking attempts can't change their contents/value.
Link to comment
Share on other sites

[quote author=rantsh link=topic=124774.msg517660#msg517660 date=1170210755]
but in that code... the constant FOO and the var $foo are 2 different things, actually if you have 2 vars $foO and $Foo, PHP treats them differently... am I wrong?
[/quote]
You are correct. However, the code example has defined 'FOO' constant at the beginning and attempts to define it again within someThirdPartyCode_NOT_AS_BAD() function, and that was what I was referring to (about PHP giving a notice on the second define attempt).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.