uncertain variables in php
if($a == 4){ echo 'ok'; }
Now displays an error because $a v开发者_开发问答ariable is not defined. my decision:
if(isset($a)){
if($a == 4){
echo 'ok';
}
}
But maybe there are better solutions?
I think it's good enough. You could merge the two if
s if you like.
if (isset($a) && $a == 4) {
echo 'ok';
}
Your solution is correct, but if you want to be 100% "clean" then you should never have to use isset(), as your variables should always be in scope. You should define $a = null at the beginning, and check if it is null.
This is how a statically typed program would work (say java). But since you are using PHP, you could decide to relax this, and play by PHP rules, by allowing use of undefined variables (which makes code more dirty, but shorter and more readable). It is up to you. In this case, change the error reporting in php.ini not to issue this kind of notices.
Ideally, you shouldn't have to do this. If $a is originally being created inside a conditional, but not under all circumstances, you should declare it and set it to null before that conditional.
Compare:
if(false)
{
$a = 4;
}
//...
if($a == 4){
echo 'ok';
}
To:
$a = null;
if(false)
{
$a = 4;
}
//...
if($a == 4){
echo 'ok';
}
Yes, that if (false)
will never set $a to 4. However, the second example will not trigger the warning.
Also, I hope you're not relying on register_globals
being on.
Otherwise, if you must use isset(), I would combine the call into one if statement, as suggested by KennyTM.
@
has done so much damage to the PHP community at large. I can't count the hours gone into debugging and fixing @
ty code.
The following solutions are shorter, but ugly (i.e. the kind of code that make seasoned programmers run away in disgust):
if (@$a == 4) // Don't show the warning in this line (*UGLY*)
echo 'OK';
or
error_reporting(error_reporting() & ~E_NOTICE); // Don't show any notice at all (*EVEN UGLIER*)
Both are considered bad practise, as you could miss an unrelated notice which could be symptomatic for some deeper problem.
精彩评论