Al wrote:
Can someone explain to me the value of using defined custom constants, in the context of good coding practice.

I don't recall ever seeing define() used in the scripts I've seen and only the characteristics are described in the my php book and the php manual; but, not the use.

Talking about constants. I've seen the most scripts and web pages, (like some Open Source projects) They declare the database access values as vars not constants. I mean Username, Password, DataBase Name or Host.

In my point of view, this info is always constant on the script life, so it will be better to declare it as constants not as vars.

I normally declare as constants anything that will not change in the scripts life. Parhaps can change from one installation to another, but no more. Specially if I'm not completly sure that the value is correct for my purposes, I prefer to declare a constant and not directly write the value everywhere. It makes me easier to read and remember, and easier to change in future if I need it.

For example, I think that :

if ($user_level == USR_LEVEL_WEBMASTER) {
    // do stuff
}

is a lot easier to read and to imagine what we are looking for than:

if ($user_level == 255) {
    // do stuff
}

Another way I use constants is when I want to pass to a function a sum of options. In this case imagine that function (Perhaps inside a class):

function draw_box($options) {
    // do stuff
}

and this constants:

define('BOX_DRAW_BORDER', 1);
define('BOX_FILL_BACKGROUND', 2);
define('BOX_SHOW_TITLE', 4);
define('BOX_MAKE_LINKS' 8);

Then, I can call the function like this:

$box_options = BOX_DRAW_BORDER + BOX_FILL_BACKGROUND + BOX_MAKE_LINKS;
draw_box($box_options);

Finally, I normally use constants to declare all literal values that must be shown in the users browser. This is a need for me, beacuse in my country (Catalunya) we are bilinguals, and I have to be able to show literals in one or other language depending on the preferences. This makes scripts translation more easy, because I have all strings in one (or two) file.

I think, we should use constants always when we have a constant value (wich not will change on scrits' life).

Regards,
Jordi.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to