0

I need to extract the value of a constant in PHP from a string. My example will explains it better than my words :)

constants.php :

define('CONNECTION_FAILED', 'Connection Error');

index.php :

include_once 'constants.php';
$success = $_GET['message']; //$success -> "CONNECTION_FAILED"

Now what I want to do is to show the value of the constant with the name present on the $success variable.

Do you know a way to do this simple thing ?

Thank you in advance

Dupuis David
  • 391
  • 2
  • 13

4 Answers4

4

You can use the constant function to get the value of a constant:

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

In your case it can be:

echo constant($success);
Dekel
  • 60,707
  • 10
  • 101
  • 129
1

Yes, you can get the value of a constant of computed name with the constant function:

define('CONNECTION_FAILED', 'Connection Error');
$success = $_GET['message']; //$success -> 'CONNECTION_FAILED'
$message = constant($success); // 'Connection error'
JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28
1

See constant http://dk.php.net/manual/en/function.constant.php ou can do constant($success)

Abdullah Razzaki
  • 972
  • 8
  • 16
1

Using constant(), you can achieve what you want. Check that its set before you do anything to avoid having Undefined constant notices.

include_once 'constants.php';
$success = '';
if (isset($_GET['message']) && constant($_GET['message']) !== null) {
    $success = constant($_GET['message']);
} else {
    // Not a valid message
    // $_GET['message'] not defined as a constant's name
}
Qirel
  • 25,449
  • 7
  • 45
  • 62