Search code examples
phpconstants

php constant can be referenced but defined() returns false


Has anyone encountered this?

var_dump(CRYPT_SHA256 == 1); // returns bool(true)
var_dump(defined(CRYPT_SHA256)); // returns bool(false)

Solution

  • Add quotation marks

    defined('CRYPT_SHA256')
    

    Otherwise, you are asking whether the value of the CRYPT_SHA256 constant is also the name of another constant....

    defined(CRYPT_SHA256) === defined('1');
    

    Edit : Add namespace

    If your constant is defined in a namespace, you must include it in the constant name.

    namespace Some\Namespace;
    
    const MY_CONST = 'value';
    
    var_dump( defined('MY_CONST') ); // false unless another constant has been defined
    var_dump( defined('Some\Namespace\MY_CONST'); // true
    

    This is not the case in the original question, but it can be a cause of the same problem too.