amflare
amflare

Reputation: 4113

How do I check if a constant is defined from a different class?

How can I see if a constant is defined in an instantiated class?

I have:

Class foo {
  const BAR = 'baz';
}

and later $foo is getting passed into a function in another class wherein I check if it is set and use its value (or a default value):

Class abc {
  public function xyz($foo)
  {
    if (defined($foo::BAR)) {
      $var = $foo::BAR;
    } else {
      $var = 'default';
    }
  }
}

But no matter what I do, I can't get it to figure out if the constant is defined. It is either defined and works, or it is not defined and throws a FatalError: Undefined class constant 'BAR' before we can get to else.

These are the various dumps I've done (that I can recall) and their outcomes:

$foo::BAR            | string 'baz' (length=3)
$foo->BAR            | null
$foo::BAR !== null   | boolean true (when set) Error (when unset)  
defined($foo::BAR)   | boolean false
defined('$foo::BAR') | boolean false
defined("$foo::BAR") | boolean false
defined('BAR', $foo) | Error

If it helps at all, I'm working in Laravel 5.4 and PHP 5.6.

Upvotes: 2

Views: 982

Answers (1)

Calimero
Calimero

Reputation: 4288

Probably works better with a class name instead of an object variable :

if(defined(get_class($foo).'::BAR')) // Do something

Upvotes: 6

Related Questions