lolalola
lolalola

Reputation: 3823

uncertain variables in php

if($a == 4){ echo 'ok'; }

Now displays an error because $a variable is not defined. my decision:

if(isset($a)){
    if($a == 4){
    echo 'ok';
    }
}

But maybe there are better solutions?

Upvotes: 3

Views: 166

Answers (5)

giraff
giraff

Reputation: 4711

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.

Upvotes: 0

Halil Özgür
Halil Özgür

Reputation: 15945

@ has done so much damage to the PHP community at large. I can't count the hours gone into debugging and fixing @ty code.

Upvotes: 0

George Marian
George Marian

Reputation: 2669

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.

Upvotes: 2

kennytm
kennytm

Reputation: 523464

I think it's good enough. You could merge the two ifs if you like.

if (isset($a) && $a == 4) {
  echo 'ok';
}

Upvotes: 14

Palantir
Palantir

Reputation: 24182

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.

Upvotes: 6

Related Questions