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

Asked

Viewed 395 times

4

In PHP, to check if a constant exists we use the function defined. 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 in a classe? How do I verify their existence?

namespace StackOverflow {

   const LANG = 'pt-br';

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

From the above example, how would you verify the existence of StackOverflow\LANG and StackOverflow\StackOverlow::MY_CONSTANT?

2 answers

3


You will use the function defined().

In both cases you need to inform the namespace complete:

<?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";

}
  • If I wanted to check the constant that is outside the scope of namespace, I would have to do so defined('\MY_CONSTANT')?

  • 1

    That. If you have a constant in the global namespace (\\) and you need to check it inside a namespace you use the bar.

  • Interesting! Works with static also!

  • the part with static vi here.

  • Like the static works with the current class, so the guy defined the `defined('Static::CONST') within the abstract class. Very useful :)

3

you can use the function defined but don’t 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.