Curly braces or colon-endif statements in PHP - which one provides better performance and code compatibility?

前端 未结 5 1748
耶瑟儿~
耶瑟儿~ 2021-01-07 22:03

I was looking through many snippets of code, and I have found that people can use the following two methods in an if statement:

Method 1:



        
相关标签:
5条回答
  • 2021-01-07 22:32

    As I've seen until now, in my app, there is no difference between them, but you can have a lot of problem if you'll mixt them without a rule because it's possible to get some errors and you will search a curly but you have not used curly. Choose one syntax an use exclusive.

    0 讨论(0)
  • 2021-01-07 22:36

    This alternative syntax is in no way different than the, perhaps, more familiar syntax. Just don't mix the two. Similar syntax exists for while, for, foreach, and switch.

    Typically you should choose your preferred syntax based upon readability, and your teams preference.

    What really might throw you is when you begin to see "if statements" which misuse logical conjunction operators like the following:

    isset( $value ) AND print( $value );
    
    0 讨论(0)
  • 2021-01-07 22:43

    The only difference is seen in very large documents and projects. My company uses braces rather then endif, endelse... as we work on very large projects. When you compare file sizes there is a benefit to using braces. Smaller files load faster so we work to reduce every byte we can. We comment out the end brace to make it easier to identify on testing and then delete all comments for production.

    0 讨论(0)
  • 2021-01-07 22:52

    Most of the time the alternative (endif) syntax is used in view scripts. It's often hard to see/notice the end of an if statement since a curly brace only takes up one character, when you're at the bottom of a file, it's hard to tell if it's the end of an if or a foreach. For example:

    <?php if ($condition): ?>
    
        <div>a huge block of html</div>
    
    <?php endif; ?>
    
    0 讨论(0)
  • 2021-01-07 22:55

    They are both exactly equivalent. Consult your organization's style guide to determine which you should use.

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