2

My class looks similar to this:

class Foo {
    const UNKNOWN = 2;

    public function doStuff($var) {
        if($var==UNKNOWN) {
            echo "Unknown state";
            return;
        }
        // other stuff
    }
}

However, I'm getting this error in doStuff():

Use of undefined constant UNKNOWN - assumed 'UNKNOWN'

What am I doing wrong? Can't I define custom constants?

3 Answers 3

10

You must use self:: or the class name when accessing the constant in your class:

if($var == self::UNKNOWN) {
    echo "Unknown state";
    return;
}
Sign up to request clarification or add additional context in comments.

4 Comments

FYI, The question-asker changed the code in their question after I posted my answer which is why my answer doesn't match the code int their question.
Yeah I updated it to be correct, sorry about that. Just waiting for the 13 minutes or whatever is needed before I can accept.
@JohnConde Much better ;)
@MightyPork get even uglier when the constant is an array
4

Documentation has the example of defining the constants in the PHP class.

self:: will help 


  class Constants
{
  //define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.

  const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
  const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.

  public static function getMinValue()
  {
    return self::MIN_VALUE;
  }

  public static function getMaxValue()
  {
    return self::MAX_VALUE;
  }
}

Comments

0

for using every dynamic field in php you must call $this->field and for using every static field and const in php you must call self::field

example:

    class ApiController {

          public static $static= "";
          public $dynamic= "";

          public function __construct() {
          $a=$this->$dynamic;
          $b=self::$static;
    }
  }

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.