0

EDIT:

THIS QUESTION hasnt' been already asked, so, before CLOSING, read it at first.

question:

there are 3 possible variations:

define('my_constant',  'something');
// or
define('my_constant',  '');
// or
'my_constant' not defined at all

is there shortest way, rather than:

if (defined('my_constant') && my_constant!='') 

p.s. if(!empty(my_constant)) throws error if not defined..

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    Have to disagree with the close-as-duplicate. This is not an "exact duplicate": this question asks how to combine checking whether the constant is defined (ie: the other question) with empty-checking, and specifically how to do so in the shortest way. – kander Aug 12 '16 at 09:30
  • Since you specifically asked for the Shortest Way: ```if(!empty(@constant('MY_CONSTANT')) { ... }``` - the constant function will return either the value of the constant, or NULL if not defined. It will throw a warning in that case, though. Note that I'm not saying this is the Right Way (with the error-silencing and everything). – kander Aug 12 '16 at 09:32
  • 1
    It is not a duplicate, in second one nobody is checking if constant is empty – Rafal Kozlowski Aug 12 '16 at 09:40
  • 1
    @kander using quiet or as I like to call 'shut up' operator @ is a really bad practice. – Rafal Kozlowski Aug 12 '16 at 09:43
  • 1
    Definitely a bad practice - like I said, it's not the right way. If I could still post an answer I'd have elaborated on that. – kander Aug 12 '16 at 09:56
  • THIS **IS NOT DUPLICATE**, why you've closed ?!!! – T.Todua Aug 12 '16 at 10:44
  • what is a shortest way anyway? I can define a function `_` that will do the check that you do and is only 1 character long. Is this your definition of shortest? – Elzo Valugi Aug 12 '16 at 13:44

2 Answers2

0
if (!defined('MY_CONSTANT')) {
    die("constant is not defined");
}
if (empty(MY_CONSTANT)) {
    die("constant is defined, but empty");
}

OR

if (!defined('MY_CONSTANT') || empty(MY_CONSTANT)) {
    die("constant is not defined or empty");
}
Rafal Kozlowski
  • 720
  • 5
  • 12
0

Joomla use this all over the place:

defined('_JEXEC') or die;

Documentation on php.net

philipp
  • 15,947
  • 15
  • 61
  • 106