Technically in PHP you can also do this:
if ($my_parameter = $this->params->get('my_parameter', 'default_value'))
{
...
$xpto = $my_parameter;
...
}
This assigns the variable and then checks that the variable is 'true', which in PHP means that it isn't null
, false
, ''
, or 0
. So depending on your default value, the if statement could be unnecessary.
My recommendation for any code style question is to avoid duplication as much as possible. I don't like the second method, because you've duplicated the default value. If you ever decide to change that default value, you have to remember to update it in two places. (And even if that sounds silly today, you will likely forget to update both places at some time, so save yourself the trouble and only define a default value once!)
The first method allows you to define that value once, in that spot. (You could also do things like add a class constant with the default value and then reference that to avoid duplicating the value.)
On whether you should assign it to a variable or not, the main question is do you use the variable again? If you just need to check that it is true, put the call to get the value in the if
statement and don't assign it to a variable. If you want to check that the param is one of several options, maybe try a switch:
switch($this->params->get('my_parameter', 'default_value')) {
case 'option_a':
...
break;
case 'option_b':
...
break;
default:
...
}
Finally, if you are actually doing things with that value (either math or printing it to something), store it in a variable!