Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a class constant exists

Tags:

php

constants

How can I check if a constant is defined in a PHP class?

class Foo {     const BAR = 1; } 

Is there something like property_exists() or method_exists() for class constants? Or can I just use defined("Foo::BAR")?

like image 213
Martin Majer Avatar asked Jun 11 '14 09:06

Martin Majer


People also ask

How do you know if a constant exists?

To check if constant is defined use the defined function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null or false the function will still return true .

How do you check constant is exists in PHP?

Note: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

How check is defined in PHP?

PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

What is the purpose of constant () function?

The constant() function returns the value of a constant. Note: This function also works with class constants.


Video Answer


2 Answers

You can check if a constant is defined with the code below:

<?php if(defined('className::CONSTANT_NAME')){   //defined }else{   //not defined } 
like image 135
Daan Avatar answered Sep 21 '22 13:09

Daan


Yes, just use the class name in front of the constant name:

defined('SomeNamespace\SomeClass::CHECKED_CONSTANT'); 

http://www.php.net/manual/en/function.defined.php#106287

like image 43
Savageman Avatar answered Sep 18 '22 13:09

Savageman