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
if(!defined('BASEPATH')) {
define('BASEPATH', '/mnt/www');
}
http://us3.php.net/manual/en/function.defined.php
Use defined() function
if(!defined("constantname")) {
define("constantname", "value");
}
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).
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.
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;
}
?>
Use defined() and define().
if (!defined('BASEPATH')) {
define('BASEPATH', '/mnt/www');
}