PHP’s wonderful pseudo-functions
Thursday, 23 August 2012
There is a pseudo-function in PHP called empty
, that tells you whether a variable is “empty” for someone’s definition of empty. The empty string, zero, null, and undefined variables are all considered to be empty.
[php]
<?php
$x = null;
echo empty($x); // prints "1"
echo empty($nothere); // prints "1"
[/php]
Well, how did they make it work for undefined variables? They made empty
a language construct, not a function, so that its argument isn’t evaluated before the empty check happens. This leads to some great errors:
[php]
$x = 0;
echo empty($x); // prints "1"
echo empty(0); // PHP Parse error: syntax error, unexpected T_LNUMBER in php shell code on line 1
[/php]
Or better yet,
[php]
function y() { return 0; }
echo y(); // prints "0"
echo empty(y()); // PHP Fatal error: Can’t use function return value in write context in php shell code on line 1
[/php]
PLT is basically magick.