How to check if a defined constant exists in PHP?

后端 未结 6 497
一整个雨季
一整个雨季 2020-12-29 19:35

So I\'m using a PHP framework called fuelphp, and I have this page that is an HTML file, so I can\'t use PHP in it. I have another file tha

相关标签:
6条回答
  • 2020-12-29 19:47

    First, these are not variables, but constants.

    And you can check their existence by using the defined() function :

    bool defined ( string $name )
    

    Checks whether the given constant exists and is defined.

    0 讨论(0)
  • 2020-12-29 19:48

    Check using defined('CONSTANT') function.

    An example from the 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;
    }
    ?>
    
    0 讨论(0)
  • 2020-12-29 19:50

    With defined you'll have to do something like that:

    if (defined("CONST_NAME"))
        $value = CONST_NAME; 
    

    This will work, but you'll could get an annoying error message in your code editor (in my case Visual Studio Code with PHP Inteliphense extension) for the second line, since it wont find CONST_NAME. Another alternative would be to use the constant function. It takes an string as the constant name and returns null if the constant is not defined:

    $value = constant("CONST_NAME");
    if ($value != null)
    {
        // Use the value ...
    }
    

    Since you passed the const name as a string, it wont generate an error on the code editor.

    0 讨论(0)
  • 2020-12-29 19:57

    Use defined() function, for example:

    if (defined('VAR_NAME')) {
        // Something
    }
    
    0 讨论(0)
  • 2020-12-29 19:58

    here's a cooler & more concise way to do it:

    defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');
    

    credit: daniel at neville dot tk https://www.php.net/manual/en/function.defined.php#84439

    0 讨论(0)
  • 2020-12-29 20:12

    I take it you mean CONSTANTS not variables! the function is defined();

    see here: defined

    0 讨论(0)
提交回复
热议问题