tags:

views:

195

answers:

2

i have doubt on this particular problem : Global variabe initiation. i got this code and has global variable named conditional_random here :

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

}

As it's name, the global variable (conditional_random) can be or not initiate before the hello_testing function been called.

So, what happen to my validation via isset() when $conditional_random is not initiate before the hello_testing function ? will it failed to check or it will always be true cause by the 'global' ?

+2  A: 

Global sets the variable. Therefore isset($some_globald_variable) will always return true.

The better option is empty()

 if(empty($globald_variable))
 {
 // variable not set
 } 
Chacha102
don't want to sound like an arse :) but you forgot one parenthesis in your `if` statement :)
Gabriel
The variable does get created, but it's initialized as null. isset returns false given a variable with a null value.
chris
+5  A: 

Well, why don't you just test ? ;-)

Note : Not as easy as you'd think -- read the full answer ;-)


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

hello_testing();

I get no output -- which indicates isset returned false.


Calling the function, after setting the variable :

$conditional_random = 'blah';
hello_testing();

I get an output :

foo is inside

Which indicates 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()

Which means that a better test would be :

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

hello_testing();

And this displays :

null

No Notice : the variable exists ! Even if null.

As I didn't set the variable outside of the function, it shows that global sets the variable -- but it doesn't put a value into it ; which means it's null if not already set outside the function.


While :

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

hello_testing();

Gives :

Notice: Undefined variable: conditional_random

Proves that notices are enabled ;-)

And, if global didn't "set" the variable, the previous example would have given the same notice.


And, finally :

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

$conditional_random = 'glop';
hello_testing();

Gives :

string 'glop' (length=4)

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

Pascal MARTIN