Search code examples
phpconstantsdefined

PHP defined not working?


I have a config file that I include early in my program and set this

define('BASE_SLUG','/shop');

I include another file later with these lines

echo BASE_SLUG;
if (defined(BASE_SLUG)) {
  echo ' - yes';
} else {
  echo ' - no';
}

And my output is

/shop - no

how is this possible? BASE_SLUG has the value of /shop and I can echo it, but one line later it says it is not defined


Solution

  • Here is the function prototype for defined

    bool defined ( string $name )
    

    You can see that it expects a string value for a constant name. Yours isn't a valid string.

    if (defined(BASE_SLUG)) {
    

    Should have the name of constant inside quotes, like :

    if (defined('BASE_SLUG')) {
    

    Read this note from PHP Manual

    <?php
    /* Note the use of quotes, this is important.  This example is checking
     * if the string 'TEST' is the name of a constant named TEST */
    if (defined('TEST')) {
        echo TEST;
    }
    ?> 
    

    Source