8

Goto your Christmas presents with PHP 5.3

 2 years ago
source link: http://schlueters.de/blog/archives/94-Goto-your-Christmas-presents-with-PHP-5.3.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Goto your Christmas presents with PHP 5.3

2008-12-25 12:17:00

Over the last few days I already mentioned a few hidden gems from PHP 5.3. Now at Christmas I wanted to take a look at some new language feature of the upcoming PHP version:

Added "jump label" operator (limited "goto"). (Dmitry, Sara)

The entry is a imprecise on purpose, since it's not to be advertised too much to not be abused too much, but well, you're reading this on Christmas instead of spending time with your family, so I guess you're a geek and know already: PHP 5.3 introduces not only namespaces but also goto. Yes it's a "goto label;" the limitations i, mentioned in the NEWS entry, are: You can only jump within the same execution unit (function or global part of the same file file) and you can't jump into loops.

When you know about goto I'm sure you know it's bad, so why did we added? - Well there's a very limited set of problems where it's ok. One is generated code, a code generator using goto can be written way better than without goto and nobody is supposed to read that code anyways. The second situation is when having a longer piece of code, where situations might occur where you cancel execution sin the middle of the code but want to do some cleanup nonetheless. A short pseudo-code example:

<?php
function process_file($filename) {
    $fp = fopen($filename, "r");
    if (!$fp) {
        goto cleanup;
    }

    $row = fread($fp, 1024);
    // do something with the row
    if ($error_while_processing) {
        goto cleanup;
    }

    $a_few_bytes = fread($fp, 4);
    // do something again ...
        if ($error_while_processing) {
        goto cleanup;
    }

    /* ... */
cleanup:
    fclose($fp);
}

?>

There are alternatives available, like wrapping this all in loops and using break or wrap it in an try {} catch block and throw exceptions, but goto can be cleaner. So have fun and use it with care!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK