Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP const not working?

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?

like image 892
MightyPork Avatar asked Aug 14 '26 11:08

MightyPork


1 Answers

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

if($var == self::UNKNOWN) {
    echo "Unknown state";
    return;
}
like image 70
John Conde Avatar answered Aug 17 '26 01:08

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!