How to check if a constant exists in the class or in a namespace?

4

In PHP, to check if a constant exists we use the defined function. As below, for the two cases of constant declaration:

const MY_TEST_1 = 'my test 1';

define('MY_TEST_2', 'my test 2');

var_dump(defined('MY_TEST_1'), defined('MY_TEST_2')); // true, true

And when I declare a constante in a namespace or a classe ? How do I check the existence of these?

namespace StackOverflow {

   const LANG = 'pt-br';

   class StackOverflow
   {
        const MY_CONSTANT = 'minha constante';
   }
}

From the example above, how would you check for StackOverflow\LANG and StackOverflow\StackOverlow::MY_CONSTANT ?

    
asked by anonymous 19.06.2015 / 14:06

2 answers

3

You will use the defined() function.

In both cases you need to enter the complete namespace :

<?php

namespace StackOverflow {

   const LANG = 'pt-br';

   class StackOverflow
   {
        const MY_CONSTANT = 'minha constante';

        public static function hasConst($const)
        {
            return defined("static::$const");
        }

   }

}

namespace {

    if (defined('StackOverflow\LANG')) echo "Opa";

    if (defined('\StackOverflow\StackOverflow::MY_CONSTANT')) echo "Opa";

}
    
19.06.2015 / 14:08
3

You can use the defined function but do not forget to pass the class name together

<?php

namespace StackOverflow {

   const LANG = 'pt-br';

   class StackOverflow
   {
        const MY_CONSTANT = 'minha constante';
   }
}

namespace teste {
    var_dump(defined("LANG")); //false
    var_dump(defined("MY_CONSTANT")); //false
    var_dump(defined("StackOverflow\LANG")); //true
    var_dump(defined("StackOverflow\StackOverflow::MY_CONSTANT")); //true
}
    
19.06.2015 / 14:23