Reputation: 22674
Suppose I have a conditional statement without brackets in a function:
function get_user_id()
{
if ($something) $this->some_function($str);
return array('user_id' => $user_id);
}
I think bracketless statements are bad practice... I want to add brackets to the if-statement but where does the statement end? Does is it end at the first semicolon or the end of the function?
Which is correct:
function get_user_id()
{
if ($something)
{
$this->some_function($str);
}
return array('user_id' => $user_id);
}
or..
function get_user_id()
{
if ($something)
{
$this->some_function($str);
return array('user_id' => $user_id);
}
}
Upvotes: 1
Views: 85
Reputation: 8461
First one is correct. One of the reason is that second wont return any array if the condition is false, which is not a good practice.
if ($something)
{
$this->some_function($str);
}
return array('user_id' => $user_id);
for that you need extra code to make it fault tolerant.
Upvotes: 1
Reputation: 17451
Definitely the first version is correct. Take a look at the examples in the documentation: http://php.net/manual/en/control-structures.if.php
Upvotes: 1
Reputation: 59699
The first version is correct, as without braces, only one statement after the if
statement applies to the conditions of the if
statement.
So this:
if ($something) $this->some_function($str);
Is equivalent to:
if ($something) {
$this->some_function($str);
}
I do agree that the manual is a bit vague about this, but its example is about a single statement, and mentions that in order to incorporate additional lines to the same conditional, you would need a "statement group", denoted by curly braces:
Often you'd want to have more than one statement to be executed conditionally. Instead, you can group several statements into a statement group.
Upvotes: 4