Is it correct to create a variable within an if?

4

Is it correct to create a variable within an if?

In the code below, you create a variable inside the if, and avoid using the same filter twice.

if($id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)):
    /* Código */
endif;

What do you guys think of the practice within the IF? Is this against some standard PSR's ( PHP Standards Recommendation )?

{Thank you}

    
asked by anonymous 06.04.2016 / 22:02

1 answer

5

First of all, if is not a good example, since you can "create" the variable once only, even if it is:

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
if( $id ):
   /* Código que usa o $id, sem "criar" de novo */
endif;

But in a while already complicated, then I'll use this as an example:

while ($row = $result->fetch_row()) {
    printf ("%s (%s)\n", $row[0], $row[1]);
}

In this case, not only and correct, as is a example taken from the PHP manual .

Since in while is not only a common but often necessary case, I see no reason why I can not use it in if . In the end, legibility is always the most important. And for this, it only depends on the context where you will use it. In the above example there was certainly no gain in separating the rows.

If you have any PSR saying otherwise, you have to fix PSR instead of complicating the code.

    
06.04.2016 / 22:14