PHP6 - ifsetor() :?
by
, 02-16-2009 at 12:07 AM (2282 Views)
Web developers are constantly validating data, either through JavaScript or through a server side programming language such as PHP. If you have done any PHP development, I am sure you have been in the situation where, if a request variable is set, you want want to use that value, if it is not set, you would like it to default to a specific value. The most common and logical method to accomplish this is to use an if/else block.
The other, more dense, and in my opinion, more elegant option is to use the ternary operator.Code:if(isset($_GET['foo'])) {
$bar = $_GET['foo'];
} else {
$bar = 1;
}
More information on the ternary operator can be found in a previous blog of mine: The Ternary Operator.Code:$bar = (isset($_GET['foo'])) ? $_GET['foo'] : 1;
The ternary operator is very powerful. As you can see, it has transformed 5 lines of code into one, but programmers hate repetition. $_GET['foo'] was written twice! The situation above is encountered so often that PHP 6 will accommodate for the repetition. At first, there was going to be a new language construct called ifsetor(), however the PHP developers settled on a new operator. The previous situations will look like the following in PHP 6:The following will also be possible:Code:$bar = $_GET['foo'] ?: 1;
In other words, if $_GET['foo'] does not equal 2, it will default to 1.Code:$bar = ($_GET['foo']==2) ?: 1;










