For some time PHP has had the ability to create constant expressions with define(). The Manual says that constants must be “…only scalar and null values”. It neglects to emphasize that constant expressions are okay, too, as long as they resolve to a value that is an int, float, boolean or string value. The section devoted to constants also misses making this important point. Unfortunately, if you tried to use a constant expression with const, you were out of luck until PHP5.6 which finally fixes this issue. Hmm, does this newly found ability of const count as a bugfix or a feature? Who cares? const now works as it should! Thus, we currently have in PHP 5.6 two ways to create constant expressions, as follows:
<?php define("BAR",5); define("BAZ",BAR+10); echo "BAZ: ", BAZ; // 15 const BARO = 1; const BAZO = BARO + 1; echo "\nBAZO: ",BAZO; // 2
Nice to see PHP have some consistency in this area!
Another aspect of constants in PHP5.6 is that they can be arrays. Here’s an example:
<?php const BLA = [1,2,3]; var_dump(BLA);
Note: the constant BLA must be assigned an actual array, i.e. not a variable which evalutes as an array (see http://3v4l.org/HnNfJ) and causes an error message to display.
It does appear though that there are more consistency details to tighten up. Consider the following:
<?php $num = 1; define("ONE",$num); var_dump(ONE); // int(1)
Just try that with const, i.e. using variable $num instead of hardcoding ‘1’ and you’ll get an error; see http://3v4l.org/sqYAA.
Having more than one way to do something in PHP may be a blessing or cause you to curse, depending on whether you can easily obtain the same results.
The Manual: Migration to PHP5.6 – new features