PHP5: Miscellaneous

Posted on March 7, 2011

As I wrap-up this series of articles, let’s take a look at some new features in PHP5 that didn’t fit anywhere else and may have marginal usefulness.

Ternary Shorthand

You may be familiar with the ?: ternary operator:

$action = (!empty($_POST['action'])) ? $_POST['action'] : 'default';

The ternary operator is basically shorthand for if/else statements, so the above code is equivalent to:

if (!empty($_POST['action'])) {
  $action = $_POST['action'];
} else {
  $action = 'default';
}

In PHP5, you can now leave out the middle part. If the test expression evaluates to true, then the value of the test expression is returned. So you could do something like:

$action = ($_POST['action']) ? : 'default';

Note that this example it isn’t perfect, since empty() and casting to a boolean don’t work exactly the same. (For example, a string beginning with “0” will return false.)

Global Constants

Before PHP 5.3.0, you could only define constants using the const keyword inside a class. Now they can be defined at the global scope as well. (They still can’t be used inside functions, loops, or if statements — though you could use define() for that.)

Limited Goto

Rejoice — PHP now has a goto keyword! ;) As in other procedural languages, you can define a label and then jump to it using a goto.

It’s actually what PHP developers call a limited goto — the target label has to be in the same file and in the same context, so you can’t jump into or out of a function. You also can’t jump into a loop or switch structure, though you can jump out of one:

for($i=0,$j=50; $i<100; $i++)
{
  while($j--)
  {
    if($j==17) goto end;
  }
}
echo "i = $i";
end:
echo 'j hit 17';

You can already use break to break out of a loop or control structure, so it sounds like the only reason to use goto would be to simplify a multi-level break.

Array References in Loops

Before PHP5, the only way to change an array value inside a loop is by referencing the key:

foreach ($colors as $key => $color)
{
  $colors[$key] = strtoupper($color);
}

In PHP5, you can use a reference to modify the value directly:

foreach ($colors as &$color)
{
  $color = strtoupper($color);
}

Note that the reference is in the global scope, so if you use $color again later, you may be accidentally changing the array value.

Casting to Null

In PHP5, you can now cast a variable to null using unset:

$a = (unset)$b;

The effect is the same as the unset construct, except that it can be used on a variable other than itself.

References in Default Values

Finally, default values can now be passed by reference:

function makecoffee(&$coffeeMaker = NULL)
{
  ...
}

Leave a Reply

  1.  

    |