View RSS Feed

John

PHP6 - ifsetor() :?

Rate this Entry
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.
Code:
if(isset($_GET['foo'])) {
    
$bar $_GET['foo'];
} else {
    
$bar 1;

The other, more dense, and in my opinion, more elegant option is to use the ternary operator.
Code:
$bar = (isset($_GET['foo'])) ? $_GET['foo'] : 1
More information on the ternary operator can be found in a previous blog of mine: The Ternary Operator.

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:
Code:
$bar $_GET['foo'] ?: 1
The following will also be possible:
Code:
$bar = ($_GET['foo']==2) ?: 1
In other words, if $_GET['foo'] does not equal 2, it will default to 1.

Submit "PHP6 - ifsetor() :?" to Digg Submit "PHP6 - ifsetor() :?" to del.icio.us Submit "PHP6 - ifsetor() :?" to StumbleUpon Submit "PHP6 - ifsetor() :?" to Google

Tags: php6 Add / Edit Tags
Categories
Uncategorized

Comments

  1. Jordan's Avatar
    That looks much better than the Ternary Operator. I saw a PHP 6 book yesterday at Barnes and Noble and thought of you. Have you had the chance to read any books on 6 yet?
  2. John's Avatar
    I don't think the authors of those books can know anymore about PHP 6 than you or I do - as the only facts regarding php 6 come from the meeting notes and everything else is speculation.
  3. Brandon W's Avatar
    Not all PHP6 books show all the features of the updated language. Most of them seem to go over the functions/operators etc. that have final notes. Other than that, they show warnings on the features that might change.

    PHP6 so far is looking really good I can't wait for this new feature to come into play.