views:

216

answers:

6

I always write if statements like this:

if (...) {
    /* do something */
}

When I create topics on stackoverflow, sometimes people change this code to:

if (...)
{
    /* do something */
}

So the first { goes to a new line.

Does it make sense, what's the true way?

+4  A: 

Whitespace doesn't matter in PHP, so use whichever style you like better (or whatever style the project you're working on or company you work for uses to keep things consistent). Both forms are completely equivalent from the PHP interpreter's perspective.

Daniel Vandersluis
+2  A: 

This is something that programmers have debated for ages. It is all up to your individual stile and preference. Both ways are "Proper PHP".

Icode4food
+1  A: 

It doesn't have to go on a new line, but some people consider it best practice to do so. It's just a matter of readability, and should therefore be tailored to best suit you or the team you're working with. There is no true way.

treeface
+2  A: 

Either. The "right" one depends entirely on your coding style. I recommend you follow the one you prefer, unless you are working on existing code in which case you should follow that code's convention.

Justin Ethier
+2  A: 

It is generally the coders preference. Some projects have coding standards, such as Zend Framework or Company's will require it one way or the other. If you are coding for someone else or your company, ask for the standards. If you are helping with an open source project, such as Zend Framework, you would read their documentation on how you should format your code. If you are doing it for yourself, pick the way you prefer and stick to it / be consistent.

Brad F Jacobs
+7  A: 

I'd suggest reading Code Complete. He goes into quite depth on the subject (Devoting practically an entire chapter on it), and gives what I see as a convincing argument for #1.

He actually says not to use the second one explicitly since it fails the black box test:

if (blah) 
{
    //Foo
}

When black boxed turns into:

XXXXXXXXX
X
    XXX
X

So the opening brace is seeming like the start of the block, wheras it's not (it's just the delimiter).

Instead, he recommends either the first option (opening brace on the same line), or:

if (blah)
    {
    //Foo
}

Since it passes the black box test:

XXXXXXXXXX
    X
    XXXXXXX
X

Note: I can't remember if the closing delimiter is supposed to be inside the block or not... I don't have my copy handy, so it might be:

if (blah) 
    {
    //Foo
    }

However, it all boils down to consistency. In order for your code to be readable, you need to be consistent in how you format it. Pick a method, and then stick to it. Don't switch from file to file or routine to routine. So long as you're consistent and actually format it, don't worry about it...

ircmaxell