Isset ve PHP Genel Değişken

2 Cevap php

Ben global değişken başlatma hakkında bir sorum var.

function hello_testing() {
  global $conditional_random;
  if (isset($conditional_random)) {
      echo "foo is inside";  
  }
}

hello_testing işlev çağrılmadan önce global değişken (conditional_random) başlatılmamış olabilir.

$ Conditional_random başlatılmadı Peki, ne) (isset ile benim doğrulama olur? Başarısız olacak ya da her zaman doğru olacak?

2 Cevap

Peki, neden sadece test yok? ;-)

Note : Sandığın kadar kolay değil - tam bir cevap okudum ;-)


Calling the hello_testing(); function, without setting the variable :

hello_testing();

isset döndürdü false gösterir - Ben hiçbir çıktı alabilirsiniz.


Calling the function, after setting the variable :

$conditional_random = 'blah';
hello_testing();

Ben bir çıktı:

foo is inside

Gösterir global works as expected, when the variable is set -- well, one should not have any doubt about that ^^



BUT note that isset will return false is a variable is set, and null !
See the manual page of isset()

Hangi daha iyi bir test olacak demektir:

function hello_testing() {
  global $conditional_random;
  var_dump($conditional_random);
}

hello_testing();

Bu da gösterir:

null

Hayır Uyarı: değişken var! Bile null.

Ben fonksiyonun dışında değişken set vermedi gibi, o global sets değişkeni gösterir - ama bunun içine bir değer koymak değildir; hangi zaten işlevin dışında set değilse o null demektir.


While :

function hello_testing() {
  //global $conditional_random;
  var_dump($conditional_random);
}

hello_testing();

Verir:

Notice: Undefined variable: conditional_random

Bildirimleri etkin olduğunu kanıtlıyor ;-)

Küresel "set" değişkeni vermedi Ve eğer, bir önceki örnekte aynı haber verirdi.


And, finally :

function hello_testing() {
  global $conditional_random;
  var_dump($conditional_random);
}

$conditional_random = 'glop';
hello_testing();

Verir:

string 'glop' (length=4)

(Purely to demonstrate my example is not tricked ^^ )

Global değişkeni ayarlar. Bu nedenle isset($some_globald_variable) her zaman doğru dönecektir.

Daha iyi bir seçenek empty() olduğunu

 if(empty($globald_variable))
 {
 // variable not set
 }