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 name@example.tld 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 name@domain.tld 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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.