Undefined variables in php

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

An error is now displayed because the $ variable is not defined. my decision:

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

But could there be better solutions?

+3
source share
5 answers

I think this is good enough. You can combine the two ifif you want.

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

Your solution is correct, but if you want to be 100% “clean”, you will never have to use isset (), since your variables should always be in scope. You should determine $ a = null at the beginning and check if it is null.

(, java). PHP, PHP, undefined ( , ). . php.ini, .

+6

. $a , , null .

:

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

To:

$a = null;

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

, if (false) $a 4. .

, , , register_globals.

, isset(), if, KennyTM.

+2
source

The following solutions are shorter but uglier (i.e. the type of code that makes experienced programmers escape from 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 bad practices, as you might have missed an unrelated notification, which could be a symptom for some deeper problem.

0
source

@caused huge damage to the PHP community as a whole. I cannot calculate how many hours have passed to debug and fix @ty code .

0
source

Source: https://habr.com/ru/post/1754550/


All Articles