Constant Consistency

31 08 2014

Flickr: by better_days.geo

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.

………………………………

Suggested Reading:

The Manual: Migration to PHP5.6 – new features

PHP5.6 – looking forward

This work is licensed under a Creative Commons License

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: