phpconstantsphp4

When and how to use Constants in PHP?


I'm currently programming a website (in PHP4). I plan to save values, which do not change during runtime, in constants. Those are for example the version number of login-data for the database.

Question 1: are there any (security relevant) problems that can arise from saving data in constants?

At the moment I do the following to define and call the constant:

define("VERSION",   "1.0");
echo "Current version: ".VERSION."."; // Result: "Current version: 1.0."

There is one thing that annoys me: In case a constant is not defined, the "wrong" variable name is returned instead of e.g. NULL.

define("VERSION",   "1.0");
echo "Current version: ".VERSIONXXX."."; // Result: "Current version: VERSIONXXX."

One solution I found to get an error message and the return value "NULL" when I accidently entered a wrong constant name is using the function constant():

define("VERSION",   "1.0");
echo "Current version: ".constant("VERSIONXXX")."."; // Result: "Current version: ."

Question 2: Can I prevent in a different way, that PHP returns the name of the non-existing variable?

Question 3: Should the value of a constant in PHP always be returned using the function constant()?


Solution

  • In reverse Order:

    Question 3: No Question 2: Not really, but you can make adjustments.

    because of (Question 1:) error_reporting. You PHP webserver is configured hide some errors. If you add

    error_reporting(E_ALL);
    

    to your scripts head, you will get a

    Use of undefined constant MY_CONST - assumed 'MY_CONST'

    Error. Unfortunately it's a problem coming out of PHP's long history, that constants can be interpreted as strings.

    If you can not be shure a constant was set in the first place you can use defined

    if(defined('MY_CONSTANT') {
         //do something
    }
    

    But my personal opinion there shouldn't be many cases to need this, since the word constant alone implies a garanteed presence. The only exception I can think of is the typical header test.

    if(!defined('MY_APP_IS_PRESENT')) {
        die('You can not call this file on its own, please use index.php.');
    }
    

    And one last tipp: Go and make yourself a errorhandler function, maybe even with firephp?