3

The manual entry for constant() says that if the constant is not defined the function should return NULL. In the case of the code below, however, it gives a fatal error.

$constant = get_class($this) . '::' . $name;
$value = constant($constant);

If $name is valid, things work fine. If it's not, however, I get a fatal error "Undefined class constant ..." The manual says it should raise an E_WARNING error too but I'm not seeing this in the log file.

7
  • $constant is a variable, not a constant. Commented Jul 30, 2012 at 21:42
  • @bfavaretto: So? read Commented Jul 30, 2012 at 21:42
  • 2
    Right, now I realize the dumbness of my comment. Commented Jul 30, 2012 at 21:44
  • @Kim Prince: I am not getting a fatal error on my end. Please include a SSCCE (Short, Self Contained, Correct Example) in your question, along with your PHP version. Commented Jul 30, 2012 at 21:45
  • @Tim Cooper: I'm getting fatal here on php 5.3 Commented Jul 30, 2012 at 21:50

3 Answers 3

2

Your PHP setup may be setup to treat all errors as fatal errors. If that is the case, checking to see if the constant exists before you try to retrieve it will be a fix:

$constant = get_class($this) . '::' . $name;
$value = defined($constant) ? constant($constant) : null;
Sign up to request clarification or add additional context in comments.

1 Comment

Nope, it's likely a version-dependent behaviour
0

Just make sure the constant is defined first, and then throw an exception instead (or proceed with whatever flow you're following).

Comments

0

This error also happens with PHP 8.
See Backward Incompatible Changes

A number of warnings have been converted into Error exceptions:

  • Attempting to access unqualified constants which are undefined. Previously, unqualified constant accesses resulted in a warning and were interpreted as strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.