Preventing Undefined Error

In order to prevent getting an Undefined Variable Error, I tend to do this a lot at the top of my scripts…


	$sessMemberID = (isset($_SESSION['sessMemberID']) ? $_SESSION['sessMemberID'] : '');

	$regEmail = (isset($_SESSION['registrationEmail']) ? $_SESSION['registrationEmail'] : '');

Is there a more sophisticated approach?

Thanks,

Debbie

In PHP 5.3 you can do this:

$variable = $item ?: NULL;

There’s a discussion of this here:http://stackoverflow.com/questions/4696453/php-assign-if-not-empty

You are doing it the right way. Is there a more sophisticated approach? It depends on what you mean by sophisticated.
You can write your own session handler class, register it with php as custom session handler and inside that class you can have a logic that would allow you to
access any variable without ever generating an undefined notice.
For example you can have your session class implement ArrayAccess interface and have a logic to return null when the actual property does not exist. This way if you
do $var = $_SESSION[‘anyvar’]; it will just set $var to null and will not raise a notice.
This may be more sophisticated but it will not be more efficient as additional lines of code have to be processed.

Anyway, you can also just abstract your current logic into a separate function, for example


function getArrayVar(array $array, $var){
if(!array_key_exists($var, $array){
return null;
}

return $array[$var];

}

Then you would get your var like this:

$regEmail = getArrayVary($_SESSION, $regMail);

This way you don’t repeat your isset() … logic.