Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 842
R_User Avatar asked Nov 11 '11 20:11

R_User


Video Answer


1 Answers

  1. If you attempt to use a constant that does not exist, PHP automagically assumes it is a string instead, which is why you see VERSIONXXX.

  2. IIRC it throws a warning if you're error reporting is at the appropriate level. The best solution here is to ensure your code utilizes the proper constant names.

  3. If you know the name of the constant, it's easiest/best to use it directly. echo MY_CONSTANT
    If you don't know the name of the constant (e.g. it's name is in a variable), use constant():

    $name = 'MY_CONSTANT';
    echo constant($name);
like image 100
simshaun Avatar answered Sep 18 '22 08:09

simshaun