When you first learn PHP, and even if you already know about PHP constants and their valuable characteristics, you are likely to make your share of mistakes. One mistake that can be a bugbear is mistakenly defining values that already exist. When you define a pre-existing variable, PHP will simply adjust the value, and you must trace the change through the stream of execution as part of the debugging process. But when you do it with a constant, you are banging two rocks together. Here is how to avoid the sparks of an already defined constant.
In addition to the define() function that PHP uses to define constants, it also has a defined() function which you can use in conjunction with it. Let's say we write against a module that has the following definition:
define('MY_TEST_CONSTANT', 'example');If we then try to pass this line in our code:
define('MY_TEST_CONSTANT', 'a new value');PHP will whine:
PHP Notice: Constant TEST_CONSTANT already defined in <filename> on line <line number>It will refuse to define it again due to the immutability of constants.
To save ourselves the trouble of this notice, we can use the following line instead:
defined('MY_TEST_CONSTANT') or define('MY_TEST_CONSTANT', 'a new value');This is a way of asserting the constant definition more politely. If the name chosen is associated with a defined constant, we comply with PHP's rules for handling constants and use the value already defined. Otherwise, we get the name we want with the value we assign. Using this method can save you a lot of headache as you learn PHP. Understanding it, you can then move on to PHP datatypes or any of the other PHP tutorials listed below.
PHP Tutorials:
Apache Tutorials:
Install Apache | Basic Configuration | Apache In-Depth |
Recommend Web Hosting | Customising Apache | PHP Hosting |
Install MySQL | Basic MySQL Configuration | MySQL Configuration In-Depth |