PHP: controlla se la variabile non è definita


92

Considera questa affermazione jquery

isTouch = document.createTouch !== undefined

Vorrei sapere se abbiamo una dichiarazione simile in PHP, non essendo isset () ma letteralmente controllando un valore indefinito, qualcosa come:

$isTouch != ""

C'è qualcosa di simile a quanto sopra in PHP?


2
possibile duplicato di PHP: "Avviso: variabile non
definita

Risposte:


171

Puoi usare -

$isTouch = isset($variable);

Tornerà truese $variableè definito. se la variabile non è definita tornerà false.

Nota: restituisce TRUE se var esiste e ha un valore diverso da NULL, FALSE in caso contrario.

Se vuoi controllare false, 0ecc. Puoi quindi usare empty()-

$isTouch = empty($variable);

empty() lavora per -

  • "" (una stringa vuota)
  • 0 (0 come numero intero)
  • 0,0 (0 come un galleggiante)
  • "0" (0 come stringa)
  • NULLO
  • FALSO
  • array () (un array vuoto)
  • $ var; (una variabile dichiarata, ma senza valore)

2
isset()restituisce sempre bool.
VeeeneX

Il cast booleano è necessario? isset (...) restituisce già bool, giusto?
Cr3aHal0

1
No. Ritorna trueo false. Quindi non c'è bisogno di quel casting.
Sougata Bose

1
puoi farlo anche usando il empty()che restituirebbe false se è una stringa vuota. isset()restituirà true se è una stringa vuota, inoltre empty esegue un controllo interno di isset.
microfono

1
potresti anche fare questo: $isTouch = (bool) $variable;che farà lo stesso di isset()ed è forse un po 'meglio poiché funzionerà come empty().
microfono

20

Un altro modo è semplicemente:

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

Sarà di ritorno :

"Yes 3"

Il modo migliore è usare isset (), altrimenti potresti avere un errore come "undefined $ test".

Puoi farlo in questo modo:

if( isset($test) && ($test!==null) )

Non avrai alcun errore perché la prima condizione non è accettata.


Se usiamo $test!==nullsenza parentesi, cosa succederà? Darà errore?
Vir

No, va bene anche così.
TiDJ

7

Per verificare se la variabile è impostata è necessario utilizzare la funzione isset.

$lorem = 'potato';

if(isset($lorem)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

if(isset($ipsum)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

questo codice stamperà:

isset true
isset false

leggi di più su https://php.net/manual/en/function.isset.php


6

Puoi usare -

Operatore ternario per controllare il valore del tempo impostato da POST / GET o non qualcosa di simile

$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';

3

JavaScript dell'operatore 'rigorosa non uguale' ( !==) sul confronto con undefinednon non comporta falsesu nullvalori.

var createTouch = null;
isTouch = createTouch !== undefined  // true

Per ottenere un comportamento equivalente in PHP, puoi controllare se il nome della variabile esiste nelle chiavi del risultato di get_defined_vars().

// just to simplify output format
const BR = '<br>' . PHP_EOL;

// set a global variable to test independence in local scope
$test = 1;

// test in local scope (what is working in global scope as well)
function test()
{
  // is global variable found?
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test does not exist.

  // is local variable found?
  $test = null;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // try same non-null variable value as globally defined as well
  $test = 1;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // repeat test after variable is unset
  unset($test);
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.') . BR;
  // $test does not exist.
}

test();

Nella maggior parte dei casi, isset($variable)è appropriato. Questo è equivalente a array_key_exists('variable', get_defined_vars()) && null !== $variable. Se usi solo null !== $variablesenza precontrollare l'esistenza, incasinerai i tuoi log con avvisi perché è un tentativo di leggere il valore di una variabile non definita.

Tuttavia, puoi applicare una variabile non definita a un riferimento senza alcun avviso:

// write our own isset() function
function my_isset(&$var)
{
  // here $var is defined
  // and initialized to null if the given argument was not defined
  return null === $var;
}

// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable);   // $is_set is false

1

È possibile utilizzare la funzione isset () di PHP per verificare se una variabile è impostata o meno. L'isset () restituirà FALSE se testare una variabile che è stato impostato su NULL. Esempio:

<?php
    $var1 = '';
    if(isset($var1)){
        echo 'This line is printed, because the $var1 is set.';
    }
?>

Questo codice restituirà "Questa riga viene stampata, perché $ var1 è impostato."

leggi di più su https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/


0
if(isset($variable)){
    $isTouch = $variable;
}

O

if(!isset($variable)){
    $isTouch = "";// 
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.