Another option to use @ in PHP?

8

I do not feel very comfortable having to use @ before some variables and sessions when I make conditions, to avoid Unexpected Index error that happens when the variable or session was not initialized previously.

I wanted to know if there is some way that I can set, in a top file of my application for example, a configuration pro PHP automatically do this for all variables and sessions? Suddenly some other solution?

    
asked by anonymous 12.05.2015 / 16:29

4 answers

8

@ is not a good practice, although it may be used, what is recommended for doing variable checks is isset .

isset other than array_key_exists (which can also be used as the example of Ricardo) supports multidimensional checks and you can also check more than one variable at a time, for example:

  • Checking multidimensional arrays:

    <?php
    $test = array('a' => 1);
    
    var_dump(isset($test['a']['b'])); //Retorna bool (false)
    var_dump(isset($test['a']));      //Retorna bool (true)
    
  • Checking more than one variable at a time:

    <?php
    $a = 1;
    var_dump(isset($a)); //Retorna bool (true)
    var_dump(isset($a, $b)); //Retorna bool (false) por que $b não existe
    

    or

    <?php
    $a = array('test' => 1);
    $b = array('foo'  => 2);
    
    var_dump(isset($a['test'])); //Retorna bool (true)
    var_dump(isset($a['test'], $b['test'])); //Retorna bool (false) por que $b['test'] não existe
    

isset also supports stdClass (or variables of a class)

Details about the isset:

  • It is not a function, it is a constructor
  • If the variable is NULL or FALSE it will return false , as in the example:

    <?php
    $a = NULL;
    var_dump(isset($a)); //Retorna bool (false)
    
  • empty vs isset

    You may not want to check multiple variables at the same time, as in the example above isset ( isset($a, $b, $c, $d, $e) ), you can use empty , which in addition to verifying if the "variable exists" it also checks if it is empty in case of strings for example. Situations that empty will return TRUE :

    • "" (an empty string)
    • 0 (when an integer equal to zero)
    • "0" (zero as string)
    • NULL
    • FALSE
    • array() (an empty array)
    • var $var; (When a variable is declared in a class but has no value since it is NULL)

    The question problem

    How to suppress all notifications of undeclared variables without using @ ? In this case I would recommend using isset and creating normal variables, such as:

    $variavelA = empty($_SESSION['varA']) ? NULL : $_SESSION['varA'];
    $variavelB = empty($_SESSION['varB']) ? NULL : $_SESSION['varD'];
    $variavelC = empty($_SESSION['varC']) ? NULL : $_SESSION['varC'];
    $variavelD = empty($_SESSION['varD']) ? NULL : $_SESSION['varD'];
    

    If it sounds cumbersome, you can use a loop with foreach or for , it's a bit tricky to admit, but there are different ways to do the process, this is just one and it will depend on how your code is :

    $keys_in_session = array('a', 'b', 'user', 'ultimaatividade');
    
    foreach ($keys_in_session as $k => $v) {
        if (empty($_SESSION[$v])) {//Acaso a variável não exista na sessão ele cria ela como o valor 'NULL' para que você possa usa-la sem ocasionar
            $_SESSION[$v] = NULL;
        }
    }
    

    Consideration of use

    Despite the example with foreach , I personally recommend using only isset and empty combined with if or with ternary comparison operators:

    echo 'Resposta: ', ( empty($_SESSION['message']) ? 'sem resposta' : $_SESSION['message'] );
    

    Development Environment vs. Production Environment

    As already mentioned in the other answer, the use of error_reporting is a good practice for the production and development environment.

    • Development environment is when you are developing the software in a place where it does not affect the server / site ie on your machine for example.

    I personally always use all "on" error notifications in the development environment:

    <?php
    //No topo do script
    error_reporting(E_ALL|E_STRICT);
    

    In the production environment I always turn off all errors:

    <?php
    //No topo do script
    error_reporting(0);
    

    But it is not possible to determine all failures that may occur and all situations, so how do you know which errors occurred? For this we have 3 functions that we can use combined, error_get_last() , set_error_handler and register_shutdown_function , so you can write errors to a .txt file for example and refer to this file to check when the fault occurred, see an example in this other answer:

    link

      

    Note: It's not because you're going to turn off error messages that you should not use isset or empty , try to use E_ALL|E_STRICT to detect possible code faults and then fix them.

        
    12.05.2015 / 19:57
    6
      

    With this solution you check whether the key of the session (or any other) array exists.

    if (array_key_exists("login", $_SESSION)) {
        echo "O Usuario esta logado";
    }
    
      

    With this solution, no more notices will be displayed as Unexpected Index (that's what the question asks) but does not resolve Unexpected Index .

    To configure php.ini to not display notification messages, you should leave it as follows:

    error_reporting  =  E_ALL & ~E_NOTICE
    

    Another way is to paste this line into the start file of the .php file:

    ini_set("display_errors", "0");
    

    Another way is to paste this line into the start file of the .php file:

    error_reporting(E_ALL ^ E_NOTICE); // ira reportar todos esceto os 'notices'.
    
        
    12.05.2015 / 17:00
    1

    Follow the session_defs.php file to be included in the code setup. In this file I created the session_def function, which defines the default value for the session variable if it has not yet been defined.

    Session_defs.php file

    <?php
    function session_def($name, $value) {
        // isset: Informa se já variável foi iniciada antes
        if (!isset($_SESSION[$name]))
            return $_SESSION[$name] = $value; // Se não foi iniciada,
                                              // inicia com o valor padrão
        return $_SESSION[$name];
    }
    
    // Cria a sessão ou resume a sessão atual.
    // A partir deste ponto a variável $_SESSION é definida com os valores
    // que já foram definidos anteriormente.
    session_start();
    
    // Define os valor padrão para as variáveis de sessão que não foram iniciadas
    // com session_start.
    session_def('item1', 12345);
    session_def('item2', true);
    session_def('item3', 'string');
    
    ?>
    

    Use

    <?php
    require_once 'session_defs.php';
    ?><!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
    </head>
    
    <body>
    <pre>
    <?php
    var_dump($_SESSION); 
    ?>
    </pre>
    
    </body>
    </html>
    
        
    12.05.2015 / 16:50
    -3

    Normally this undefined index error is caused by problems in $ _POST or $ _GET.

    You can execute extract (); at the beginning of the code. So all variables come in automatically, without having to call $ _POST or $ _GET.

    Just insert at the beginning of the code:

    extract();

    This article explains in detail the solution to the error:

    link

        
    15.06.2016 / 14:59