tags:

views:

127

answers:

3

Can I set variables inside if-construct? In general, where is it allowed to set variables?

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;
+1  A: 

Yes you can and it's allowed. But the thing is that what if the IF does not run and you incorrectly handle that situation.

So usually I initialize my big vars in the widest scope of the function and temporary vars is ok to be set inside somethings.

You should be aware though in your case. That you are initializing a global variable.

Ólafur Waage
What about if I initializes the variable as a parameter of the if-function? I mean like: if( initialise_var() === false) ...
HH
If I understand right, it must set the variabless because otherwise it could not evaluate the if-statement.
HH
This part "IF does not run and you incorrectly handle that situation." needs some clarification, reason for my earlier questions.
HH
If the conditional statement doesn't run. And you expect the value later on. Then this can cause problems. Since the value isn't set.
Ólafur Waage
+2  A: 

Short answer

Yes

Long answer

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

Kamil Szot
A: 

You haven't specified what the ERROR variable is. If it being true indicates an error, set_login_session can be essentially reduced to

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

and the outer code to

return set_login_session( $passhash );

There's no need to do such explicit bool value comparisons.

And yes, it's perfectly valid to set variables in functions, but make sure the variable is set always, no matter of the code path taken, so there are no uninitialized/unexistant variables used in your code. Otherwise you're asking for trouble or, at least, big fat warnings in script output.

The $_SESSION superglobal should be present if there's a session started. If there was no ['login']['logged_in'] in it, that's fine.

macbirdie