1

Why does the following code give me an exception saying that my constant isn't defined

MyClass::myFunction(MyClass::MY_CONST); // THIS GIVES THE ERROR   

// This is the class..
class MyClass {

    const MY_CONST = 'BLA';

    public static function myFunction($key) {
        if (!defined($key)) {
            throw new Exception("$key is not defined as a constant");
        }
    }
}

I've tried with

  • if (!defined($key)) {}
  • if (!defined(self::$key)) {}
  • if (!defined(__CLASS__ . $key)) {}
3
  • It is a matter of timing, so to speak. You are trying to use the constant before you define it. Commented Oct 27, 2014 at 12:23
  • 1
    U need to pass it as string Commented Oct 27, 2014 at 12:23
  • While trying to write example code, I was wondering when would you use this? If MY_CONST wasn't defined, you wouldn't be able to use it in your first line Commented Oct 27, 2014 at 12:23

3 Answers 3

2

You have to pass it as a string:

public static function myFunction($key) {
    if (!defined('self::'.$key)) {
        throw new Exception("$key is not defined as a constant");
    }
}


MyClass::myFunction('MY_CONST');
Sign up to request clarification or add additional context in comments.

Comments

0

As Daniele D points out, for starts you're calling it with the value of the constant, not its name.

And defined needs a different syntax for the parameter when checking class constants, rather than defined constants. It should be

if (!defined('self::' . $key)) {

Comments

0

You need to pass the entire class name and constant as a string.

Like:

MyClass::myFunction('MyClass::MY_CONST');

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.