PHP Alternative Control Structures, any drawbacks?

后端 未结 5 1040
天涯浪人
天涯浪人 2021-01-21 02:14

I\'ve been working with PHP code that generates HTML without any templating, and it\'s quite spaghetti and difficult to read with the way they\'ve structured it. On

相关标签:
5条回答
  • 2021-01-21 02:45

    to answer directly: Yes, it is standard and portable and it isn't any slower. It is a simple alternative to the standard curly-brace syntax. Whether or not you choose to use it is up to you as a style choice.

    Personally, having been taught and used c-style languages my whole programming career (thus far) i prefer the curly braces with a simple comment after the end of the } curly brace that tells you what it is ending.

    0 讨论(0)
  • 2021-01-21 02:48

    The only drawback that i see is that in an editor like sublime text, there are options like "Jump to Matching Bracket" and "Expand Selection to Brackets" which wont work with the alternate syntax

    0 讨论(0)
  • 2021-01-21 02:50

    Personally, I detest them, but they're part of the language. They haven't been deprecated and I doubt they'll be removed anytime soon.

    The thing you have to be careful about is that you can't mix the two syntaxes in the same control block (as the manual page says).

    I don't find them any more readable. Identation gives enough clue. If you have blocks long enough that you see yourself using these control structures or } //end of while, you should refactor your code.

    0 讨论(0)
  • 2021-01-21 02:50

    PHP Alternative Control Structures, any drawbacks?

    Yes, you can't use % in vim to bounce between the beginning and end of the block. Just sayin.

    0 讨论(0)
  • 2021-01-21 02:51

    Is this portable?

    Yes

    Is this standard?

    Yes

    Is this slower in any significant way (I understand it takes more chars)

    I don't know.

    But imho it increases readability and maintainability very much if you use it in combination with HTML.

    Example:

    <?php foreach($array as $value): ?>
        <div>
        <?php if($value == "foo"): ?>
            <p><?php echo $value; ?></p>
        <?php endif; ?>
        </div>
    <?php endforeach; ?>
    

    vs

    <?php foreach($array as $value) { ?>
        <div>
        <?php if($value == "foo") { ?>
            <p><?php echo $value; ?></p>
        <?php } ?>
        </div>
    <?php } ?>
    

    It is just a small example but I think endif and endforeach are much easier to spot as <?php } ?>. So yes, definitely use it with HTML!

    I don't use it anywhere else though because in "normal" code I find it more difficult to read.

    0 讨论(0)
提交回复
热议问题