How to check if a object has a static variable defined?

October 26, 2018

If you have an object and you need to check if it has a const SOME_CONSTANT = 'foo' set, then you can use defined in the following way:

<?php
        class ExampleClass {
            const CONST_THAT_DOES_EXIST = 9;
            function does_it_have_const() {
            // late static binding:
                var_dump( defined('static::CONST_THAT_DOES_EXIST') );
                var_dump( defined('static::CONST_THAT_DOES_NOT_EXIST') );
                // or use self
                var_dump( defined('self::CONST_THAT_DOES_EXIST') );
            }
        }