Jump to content

Scope of variables in If statements


darth_tater

Recommended Posts

I know this is a simple question, but it's been bugging the hell out of me.

 

i am being told that i have an undefined variable - errorString - in a function, even though it *clearly* is defined w/i the scope of the function.  Can somebody please help me out?

 

[undefined variable: errorString/code]



[code=php:0]

/**
 * is fed a string email address and processes it to make sure that we're within limits:
 *
 *  	1) must not be empty
 *  	2) must not be above 50 characters
 *  	3) must be in [email protected] format
 *
 *  returns TRUE if email is valid, string (with reasons for failure) if the email is not valid
 *
 * @param string $email
 * @return boolean|string
 */
public static function data_validateEmail($email){
	// set up temporary vaiable
	$errorString;

	// check to see if the user's email is a null string
	if (empty($email)){

		$errorString .="You must supply an email address. ";

	}

	// then check to see if its under 50 characters

	if(strlen($email) > 50){

		$errorString .= "The email address can be no longer than 50 characters. ";

	}

	// then make sure it's in teh correct format
	if (!preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $email)) {

		$errorString .= "The email address must be in the [email protected] format. ";

	}



	// if we've got a valid email, return true... else, we return a string error
	if(empty($errorString)){

		return true;

	} else {

		return $errorString;

	}

}

 

 

errorString is defined at the beginning of the function, so why am i told that it is undefined when, say, the length test fails?  I know this has to be a simple solution, but ive spent almost 2 hours looking at it trying to figure it out, and have gotten nowhere.... :(

 

and yes, part of that 2 hours was searching google for information about how PHP does variable scope in functions with multiple if statements... and all i could find was that as long as the variable is defined in the function scope, it should be available within the successive if statements.

 

 

Thanks for reading![/code]

Link to comment
https://forums.phpfreaks.com/topic/223066-scope-of-variables-in-if-statements/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.