Does PHP have an equivalent of C/C++'s #ifdef?

前端 未结 6 1659
陌清茗
陌清茗 2021-02-19 05:53

I\'m trying to define a constant, but I don\'t want to redefine it if it\'s already been defined. Here\'s a C sample:

#ifndef BASEPATH
#define BASEPATH /mnt/www         


        
相关标签:
6条回答
  • 2021-02-19 06:46
    if(!defined('BASEPATH')) {
        define('BASEPATH', '/mnt/www');
    }
    

    http://us3.php.net/manual/en/function.defined.php

    0 讨论(0)
  • 2021-02-19 06:47

    Use defined() function

    if(!defined("constantname")) {
       define("constantname", "value");
    }
    
    0 讨论(0)
  • 2021-02-19 06:48

    In C, #ifdef often involves writing/enabling/disabling custom code based on whether a define exists or not. Though the OP was not looking for the answer that follows, search engine users may be interested to get an expanded answer. (This question helped me RTM to find the answer that follows.)

    If one has a .php file that is included multiple times, it can be convenient to declare a function only if it was not already declared by a prior include of the same file. Convenience, in this case, is keeping tightly-related code in the same file instead of having to put it in a separate include_once .php file and unnecessarily separate code that is not meant to be generally re-used in other contexts (files).

    Since it seems wasteful/improper to re-declare functions multiple times, it turns out that an #ifdef-like construct in PHP is possible:

    if (! function_exists('myfunc'))
    {
      function myfunc(...)
      {
        ...
      }
    }
    

    Where ... indicates your fill-in-the-blank.

    See also: function_exists (PHP 4, PHP 5) (w/ comments).

    0 讨论(0)
  • 2021-02-19 06:48

    This is condensed rewriting of Radu's answer above (and everyone else's).

    defined('BASE_PATH') || define('BASE_PATH', '/mnt/www/');    
    

    That's it. If defined('BASE_PATH') evaluates to true, the rest of the conditional never gets evaluated. If it returns false, the second half of the conditional is evaluated and BASE_PATH gets defined.

    0 讨论(0)
  • 2021-02-19 06:48

    Use defined():

    <?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)
  • 2021-02-19 06:51

    Use defined() and define().

    if (!defined('BASEPATH')) {
        define('BASEPATH', '/mnt/www');
    }
    
    0 讨论(0)
提交回复
热议问题