C++ preprocessor #define
is totally different.
Is the PHP define()
any different than just creating a var?
define("SETTING", 0);
$something = SETTING;
vs
$setting = 0;
$something = $setting;
The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.
PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
'define' operation itself is rather slow - confirmed by xdebug profiler.
Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html:
pure 'define'
380.785 fetches/sec
14.2647 mean msecs/first-response
constants defined with 'hidef' extension
930.783 fetches/sec
6.30279 mean msecs/first-response
broken link update
The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine. Here is another similar article.
The libraries the author references can be found here (apc_define_constants) and here (hidef extension).
In general, the idea of a constant is to be constant, (Sounds funny, right? ;)) inside your program. Which means that the compiler (interpreter) will replace "FOOBAR" with FOOBAR's value throughout your entire script.
So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most cases you will not notice a different because the PHP script is compiled with each run. Afai-can-tell you should not see a notable difference in speed between constants and variables unless you use a byte-code cache such as APC, Zend Optimizer or eAccelerator. Then it can make sense.
All other advantages/disadvantages of constants have been already noted here and can be found in the PHP manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With