0

I am trying to make a small PHP function which can check if a constant is defined, and if so, echo it, and if not, echo space or nothing.

Right now, the if(defined() part is not working, because the constant is being transferred to a variable inside the function.

function getConstant($constant) {  
  if(defined($constant)) {
    echo constant($constant);
  } else {
    echo '';
  }
}

The echo constant($constant) part is working fine, but I cannot check if the constant is actually defined because it is a variable now.

I cannot seem to find a solution for it

5
  • 1
    What do you mean the constant is transferred to a variable? You mean the constant's name?
    – yivi
    Commented Jan 3, 2017 at 10:02
  • 1
    All works fine 3v4l.org/a8Rgh
    – u_mulder
    Commented Jan 3, 2017 at 10:04
  • 1
    $constant must be a string with constant's name.
    – u_mulder
    Commented Jan 3, 2017 at 10:05
  • code is working fine:- eval.in/708124 Commented Jan 3, 2017 at 10:05
  • If $constant is a string which you expect will have the constant literal, code is ok. May be having namespacnig issues? Are you inside a class?
    – yivi
    Commented Jan 3, 2017 at 10:07

1 Answer 1

3
public static function isConstants($constant) {
    $oClass = new ReflectionClass(__CLASS__);
    $allConstants = $oClass->getConstants();
    if (isset($allConstants[$constant])) {
       echo $allConstants[$constant];
    } else {
       echo '';
    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.