So just to better myself I'm wondering which method is 开发者_运维知识库better for setting a variable:
Code: http://pastie.org/private/jkw9dxplv0ixovvc0omq
Method 1: Set the end variable in the if statement
-OR-
Method 2: Set a default variable and only change it's value if needed.
I hope this makes sense.
Thank in advance!
<?php
$value = 10;
$x = 'no';
if($value == 10){
$x = 'yes';
}
?>
Method two.
I think this mostly has to do with personal preference. Any performance improvements will be negligible. Of these two, I would usually go with Method 2. However, I usually use a shorthand form of Method 1 to keep everything readable and on 1 line:
$value = 10;
$x = $value == 10 ? "yes" : "no";
I prefer method 1. That way, if the case is 10, then $x is only set once. Otherwise, it is set once or twice. Not sure that it matters a lot, but it is more readable and logical too.
In my opinion is better to assign a default value and initialize variables, so i choose the second method.
If something goes wrong runtime you don't have to bother if your variable ($x) has been initialized or not.
$value = 10; $x = ($value == 10) ? "yes" : "no";
精彩评论