PHP: setting variables in an IF construct?

Is it possible to set variables inside if-construct? In general, where are variables allowed?

function set_login_session ( $passhash ) { $_SESSION['login']['logged_in'] = 1; if ( ERROR ) return false; } // Does it set the Session variable? if ( set_login_session ( $passhash ) === false) return false; 
0
source share
3 answers

Short answer

Yes

Long answer

If this script called start_session () earlier (or the session.auto_start configuration flag is set), then the session variable can be set anywhere using the $ _SESSION superglobal array.

+2
source

Yes, you can allow it. But the fact is that if IF does not start and you are not handling this situation correctly.

So usually I initialize my large vars in the widest range of functions, and temporary vars are normally set inside somethings.

You should know what is in your case. That you are initializing a global variable.

+1
source

You did not specify what the ERROR variable is. If true indicates an error, set_login_session can be significantly reduced to

 $_SESSION['login']['logged_in'] = 1; return !ERROR; 

and the external code is

 return set_login_session( $passhash ); 

There is no need to make such explicit comparisons of bool values.

And yes, this is absolutely true for setting variables in functions, but make sure that the variable is always set, regardless of the code path, so there are no uninitialized / faulty variables used in your code. Otherwise, you are asking for problems, or at least big fat warnings in the output of the script.

The superglobal amount of $ _SESSION must be present if the session has begun. If it didn't have ['login'] ['logged_in'], that's fine.

0
source

All Articles