PHP correct indentation?

2020-08-16 16:45发布

I'm a beginner PHP coder, recently I've been told I indent my code not correctly. They say this is wrong:

    if($something) {
        do_something();
        }
    else {
        something_more();
        and_more();
        }

While this is right?

    if($something) {
        do_something();
    } else {
        something_more();
        and_more();
    }

Really? I am willing to become opensource coder in nearest future so that's why I'm asking how to write code in a good way.

5条回答
做个烂人
2楼-- · 2020-08-16 17:03

CodeIgniters user guide got some great tips on how to write your code: http://codeigniter.com/user_guide/general/styleguide.html

Some are really good, but some you'll have to mix and match to get your own good style. But as said before me you should stick to one style and if you're jumping into another project you should follow the style already set. There's no right or wrong in how to style you're code, it's mostly so that you don't get lost when going back to the code after a few months.

查看更多
贪生不怕死
3楼-- · 2020-08-16 17:11

There are many Coding Standards. @Adam gave You two links, I give You another: Zend PHP Coding Standard You can choose, what You want, but You should choose most popular standard, I think.

You can use even Code Conventions for the Java It doesn't really matter.

查看更多
Explosion°爆炸
4楼-- · 2020-08-16 17:13

In many cases, coding standards say, "match the style of the file you're editing," ie. don't change conventions if the file already has a given brace and whitespace style.

I would look over the coding standards for some popular projects to get a feel for what some patch wranglers expect:

&c.

查看更多
Bombasti
5楼-- · 2020-08-16 17:15

Both ways will run just fine. Whichever is more comfortable for you and your team would be the way to go. I personally favor the second example, or something alone these lines:

if ($something)
{
  do_something();
}
else
{
  do_something_else();
  pet_the_ponies();
}

There's no real right answer to this.

查看更多
在下西门庆
6楼-- · 2020-08-16 17:23

I would recommend you follow the PEAR coding standards. Not because they're the best, or because I like them, but because they're the most common amongst popular PHP frameworks (Symfony2, Zend Framework and others follow them for the most part, little details don't really matter).

After all, that's the whole purpose of a Coding Standard. To be a standard that everyone follows, no matter whether they like it or not.

Of course, if you're coding within an existing project, do not blindly follow that, try to follow whatever coding style is used in the files you are editing.

查看更多
登录 后发表回答