Call
608.845.2900
Visit
330 Locust Dr.
Verona, WI 53593
Message
info@powderkegwebdesign.com
Powderkeg Web Design
Menu
Message Us
Matt
Matt

PHP, Constants, and You

March 30, 2015

An often underused aspect of PHP is the use of constant variable.

As defined by the PHP docs:

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Usage

The main reason for using constants is defining something you do not want to be overridden in the global namespace. Constants are called via name only instead of with the dollar sign like a regular variable.

Issues

One of the main issues we recently ran into is how constants are evaluated. When trying to reference a constant that is undefined, it will not return null like a regular variable. Instead, they return the constant name as a string value.

As you can see, constants do not conform to how regular variables are evaluated.

Solution

Instead of using the popular !$my_var shorthand, you should always use the constant() function.

Matt
Matt
Technical Account Manager

Matt is a skilled and nimble programmer that assists the entire team wherever help is needed. He has exceptional troubleshooting skills, is an extremely fast coder, and has strong database skills.