This question already has an answer here:
I've been working on a php course, and one of the exercises has us create a config.php file wherein we define database constants.
I know the standard way of doing this, which is:
define("NAME", "value");
However, this exercise has it written differently. It's in if/else shorthand. Now I know it's correct, because it works. But I don't understand WHY it works. Hopefully it's a simple answer for you more experienced devs:
defined('DB_SERVER') ? null : define('DB_SERVER', 'localhost');
The way I read it, it's checking to see if DB_SERVER is defined. If it's true, then it sets it to NULL ?
Why would it NULL out the value of that constant if it's already defined?
</div>
If it's defined, it runs the expression null
, which is essentially a noop (does nothing). Otherwise, it actually runs define
. You could write this as defined('DB_SERVER') ?: define('DB_SERVER', 'localhost')
nowadays, but I personally think that it is confusing. I would have simply written it as:
if (!defined('DB_SERVER')) {
define('DB_SERVER', 'localhost');
}
Here is the long-hand form:
if ( defined('DB_SERVER') )
{
// Do nothing
}
else
{
define('DB_SERVER', 'localhost');
}
In English:
If someone already defined 'DB_SERVER', leave it alone
Otherwise, define it with the value of 'localhost'