Jump to content

Recommended Posts

I have a script that uses two functions and a simple switch statement.

 

If I wanted to take the value of variables from function 1 and use them in function 2, would I have to declare them global in both functions, function 1, function 2, or outside the functions?

 

For example

<?php

function function_1() {
//Here?
global $variable_1;
$variable_1 = hello world;
return $variable_1
}

function function_2() {
//Or Here?
global $variable_1;
echo $variable_1
}

//Or here?
global $variable_1

//Or in all three places? I want the variable to be available everywhere in the script!
?>

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/
Share on other sites

Do not use globals, unless they exist in the global scope by default.

 

I'm still not understanding, though. I know that if you have a variable outside a function, you have to declare it "global" within a function to use it in that particular function, but how would you use a variable in the main script that's inside a function, and how would you use a variable in 1 function that's value is declared in another?

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188139
Share on other sites

Do not use globals, unless they exist in the global scope by default.

 

I'm still not understanding, though. I know that if you have a variable outside a function, you have to declare it "global" within a function to use it in that particular function, but how would you use a variable in the main script that's inside a function, and how would you use a variable in 1 function that's value is declared in another?

 

No, you don't need to declare it global at all.  Functions have argument/parameter lists, which allow you to pass in variables.

 

function myFunc($arg1, $arg2)
{
   echo "Hi, these values were passed in through my argument list: $arg1 - $arg2";
}

$val1 = "Forrest";
$val2 = "Gump";

myFunc($val1, $val2);

 

Globals are the exact opposite of what you should be using, for many reasons.  They make code hard to read, difficult to maintain, and introduce hidden requirements for the function itself.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188147
Share on other sites

Well, and to actually answer the question you asked... in this situation you could do something like

 

<?php

function function_1() {
$variable_1 = "hello world";
return $variable_1;
}

function function_2($output) {
echo $output;
}

$var1 = function_1(); // This will make $var1 equal to the value returned from function_1
function_2($var1); //This will "pass" the variable that now contains the result of function_1 to function_2 to be displayed

?>

 

Hope that helps

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188159
Share on other sites

Well, and to actually answer the question you asked... in this situation you could do something like

 

<?php

function function_1() {
$variable_1 = "hello world";
return $variable_1;
}

function function_2($output) {
echo $output;
}

$var1 = function_1(); // This will make $var1 equal to the value returned from function_1
function_2($var1); //This will "pass" the variable that now contains the result of function_1 to function_2 to be displayed

?>

 

Hope that helps

 

Okay, that makes sense, but it still does not solve my problem. My script is a long one with lots and LOTS of variables, and I want about half of them to be accessible between both functions, as well as the main script. As my functions don't necessarily return a single variable, I can't perform the method you demonstrated above.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188185
Share on other sites

Sounds like your overall design may be flawed.  Can you give a relevant example of what you're trying to do, and why you need these variables?

 

Here's my code:

<?php

//****************************************
//***************Includes***************
//****************************************
require_once "arrays.php";
require_once "connect.php";
require_once "select.php";

//****************************************
//****************Action******************
//****************************************
switch ($_GET["action"] {
default:
case "index":
	//If the user is not a member already
	if (!$_SESSION["member"]) {
			display_form();
	} else {
		//Tell them that they are already a member
		echo "You are already a member.";
	}
	break;
case "process":
	//If the user is not logged in (not a member)
	if (!$_SESSION["member"]) {
		//And if the submit button has been clicked...
		if (isset($nm_submit)) {
				//Process the registration form
				process_form();
		} else {
			//If the user did not click the submit button
			echo "Either you have not filled out all of the information or you ended up her by mistake! Please hit the back button to start over.";
		}
	} else {
		//If the user is logged in, tell them they are already a member
		echo "You are already a member.";
	}
	break;
}

//****************************************
//***************Functions****************
//****************************************
//........................................
//........Function 1: display_form()......
//........................................

function display_form() {

global $mysql_connect;

echo "<form name='registration_form' action='?action=process' method='post'>

<label for='name'>*Name: </label>
<input type='text' name='name' id='name' value='$nm_name'>

<label>*Birthdate: </label>";

$dates_months_select = "<select name='bd_month' id='bd_month'>";
foreach ($dates_months as $value => $label) {
	$dates_months_select .= "<option value='$value'";
		if ($nm_bd_month == $value) {
			$dates_months_select .= " SELECTED";
		}
	$dates_months_select .= ">$label</option>";
}
$dates_months_select .= "</select>";
echo $dates_months_select;

$dates_days_select = "<select name='bd_day' id='bd_day'>";
foreach ($dates_days as $value => $label) {
	$dates_days_select .= "<option value='$value'";
		if ($nm_bd_day == $value) {
			$dates_months_select .= " SELECTED";
		}
	$dates_days_select .= ">$label</option>";
}
$dates_days_select .= "</select>";
echo $dates_days_select;

$dates_years_select = "<select name='bd_year' id='bd_year'>";
foreach ($dates_years as $value => $label) {
	$dates_years_select .= "<option value='$value'";
		if ($nm_bd_year == $value) {
			$dates_years_select .= " SELECTED";
		}
	$dates_years_select .= ">$label</option>";
}
$dates_years_select .= "</select>";
echo $dates_years_select;

echo "<label for='country'>*Country: </label>";

$regions_countries_select = "<select name='country' id='country'>";
foreach ($regions_countries as $value => $label) {
	$regions_countries_select .= "<option value='$value'";
		if ($nm_country == $value) {
			$regions_countries_select .= " SELECTED";
		}
	$regions_countries_select .= ">$label</option>";
}
$regions_countries_select .= "</select>";
echo $regions_countries_select;

echo "<label for='region'>*State/Region: </label>
<input type='text' name='region' id='region' value='$nm_region'>

<label for='gender'>*Gender: </label>
<label>Male</label>
<input type='radio' name='gender' id='gender_male' ";

if ($nm_gender == "Male") { 
	echo "SELECTED >"; 
} 

echo "<label>Female</label>
<input type='radio' name='gender' id='gender_female' ";

if ($nm_gender == "Female") { 
	echo "SELECTED >"; 
}

echo "<label for='website'>Website: </label>
<input type='text' name='website' id='website' value='$nm_website'>

<label for='email'>Email: </label>
<input type='text' name='email' id='email' value='$nm_email'>";
if ($nm_field_fm_em) { echo $nm_field_fm_em_msg; }
if ($nm_field_ex_em) { echo $nm_field_ex_em_msg; }

echo "<label for='username'>Username: </label>
<input type='text' name='username' id='username' value='$nm_username'>";
if ($nm_field_fm_un) { echo $nm_field_fm_un_msg; } 
if ($nm_field_ex_un) { echo $nm_field_ex_un_msg; }

echo "<label for='password'>Password: </label>
<input type='password' name='password' id='password'>";
if ($nm_field_mt_pw) { echo $nm_field_mt_pw_msg; }

echo "<label for='password_confirm'>Confirm Password: </label>
<input type='password' name='password_confirm' id='password_confirm'>";
if ($nm_field_mt_pw) { echo $nm_field_mt_pw_msg; }

echo "<input type='check' name='newsletter' id='newsletter' CHECKED>
<label for='newsletter'>Sign me up for the newsletter!</label>

<input type='check' name='tos' id='tos'>
<label for='tos'>I agree to the terms of service.</label>
<input type='hidden' name='date' id='date' value='";

echo date('F d, Y') . "'>";

echo "<input type='hidden' name='time' id='time' value='"; 

echo date('g:I:sa') . "'>";

echo "<input type='submit' name='submit' id='submit'>

<input type='reset' name='reset' id='reset'>
</form>";

}
    
//........................................
//........Function 2: process_form()......
//........................................

function process_form() {

global $mysql_connect;

//****************************************
//**************Variables***************
//****************************************
//--------------------------------------------------
//---------------Error Trapping---------------
//--------------------------------------------------
$nm_field_fm_un_msg = "*Username must start with a letter and can only contain numbers, underscores, and hyphens.";
$nm_field_fm_em_msg = "*You have not entered a correct email format.";
$nm_field_ex_un_msg = "*This username already exists!";
$nm_field_ex_em_msg = "*This email address is already in use!";
$nm_field_mt_pw_msg = "*The passwords you entered do not match!";

//--------------------------------------------------
//----------------Invalid Fields----------------
//--------------------------------------------------
$_SESSION["nm_field_fm_un"] = false;
$_SESSION["nm_field_fm_em"] = false;
$_SESSION["nm_field_ex_un"] = false;
$_SESSION["nm_field_ex_em"] = false;
$_SESSION["nm_field_mt_pw"] = false;

//--------------------------------------------------
//--------------Form Elements--------------
//--------------------------------------------------
//"Strips" any slashes from values and converts html tags into ascii characters; also prevents mysql injection attacks
$nm_name = htmlentities (stripslashes (mysql_real_escape_string ($_POST["name"])));
$nm_region = htmlentities (stripslashes (mysql_real_escape_string ($_POST["region"])));
$nm_website = htmlentities (stripslashes (mysql_real_escape_string ($_POST["website"])));
$nm_email = htmlentites (stripslashes (mysql_real_escape_string ($_POST["email"])));
$nm_username = htmlentities (stripslashes (mysql_real_escape_string ($_POST["username"])));
$nm_password = htmlentities (stripslashes (mysql_real_escape_string ($_POST["password"])));

//Drop-downs, radio groups, check boxes, and submit buttons
$nm_passwordconfirm = $_POST["password_confirm"];
$nm_date = $_POST["date"];
$nm_time = $_POST["time"];
$nm_country = $_POST["country"];
$nm_gender = $_POST["gender"];
$nm_submit = $_POST["submit"];
$nm_birthdate = $nm_bd_month . " " . $nm_bd_day . ", " . $nm_bd_year;
$nm_bd_month = $_POST["bd_month"];
$nm_bd_day = $_POST["bd_day"];
$nm_bd_year = $_POST["bd_year"];
$nm_age = $current_year - $nm_bd_year;
$nm_subscribe = $_POST["newsletter"];
$nm_tos = $_POST["tos"];

//--------------------------------------------------
//--------------Miscellaneous---------------
//--------------------------------------------------
//Get current year
$current_year = echo date('Y');

//****************************************
//*********Initial If Statements*********
//****************************************
//Check Email Format
if(!ereg("^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$", $nm_email)) {
	$nm_errors_found = true;
	$_SESSION["nm_field_fm_em"] = true;
}

//Check Username Format
if(!ereg("^[[:alpha:]](\_)*(\-)*([a-z0-9-A-Z])*", $nm_username)) {
	$nm_errors_found = true;
	$_SESSION["nm_field_fm_un"] = true;
}

//Check To See If Email Already Exists
$email_check = mysql_query("SELECT email FROM fans WHERE email = '$nm_email'"); 
$do_email_check = mysql_num_rows($email_check);
if ($do_email_check > 0) {
	$nm_errors_found = true;
	$_SESSION["nm_field_ex_em"] = true;
}

//Check To See If Username Already Exists
$username_check = mysql_query("SELECT username FROM fans WHERE username = '$nm_username'"); 
$do_username_check = mysql_num_rows($username_check);
if ($do_username_check > 0) {
	$nm_errors_found = true;
	$_SESSION["nm_field_ex_un"] = true;
}

//Check To See If Both Passwords Match
if ($nm_password  != $nm_passwordconfirm) {
	$nm_errors_found = true;
	$_SESSION["nm_field_mt_pw"] = true;
}

//If errors were found, refresh page to show login form
if ($nm_errors_found) {
	display_form();
//If no errors were found...
} else {
	//Register member
	mysql_query(INSERT INTO fans (id, name, birthdate, country, region, gender, website, email, username, password, date_registered, time_registered, age) VALUES ("", $nm_name, $nm_birthdate, $nm_country, $nm_region, $nm_gender, $nm_website, $nm_email, $nm_username, $nm_password, $nm_date, $nm_time, $nm_age));

	//If member clicked the "subscribe to newsletter" box, add member to table "subscribers"
	if (isset($nm_subscribe)) {
		mysql_query(INSERT INTO fans_subscribers (username, email) VALUES ($nm_username, $nm_email));
	}

	//Insert member into "offline" table; member remains in this table until he/she logs in for the first time
	mysql_query(INSERT INTO fans_offline (username) VALUES ($nm_username));

	//Close connection
	mysql_close;

	//Display "welcome" message
	echo "Welcome, $nm_username! You may now proceed <A HREF=\"../login.php\">here</A> to login.";

	//Empty error values from session array
	unset ($_SESSION["nm_field_fm_un"]);
	unset ($_SESSION["nm_field_fm_em"]);
	unset ($_SESSION["nm_field_ex_un"]);
	unset ($_SESSION["nm_field_ex_em"]);
	unset ($_SESSION["nm_field_mt_pw"]);

}

}

?>

 

Follow it closely. If you look, in the function process_form(), there are error values which are set to true if the fields are incorrect. I want if statements in the html form of the display_form function to check to see if the error variables from process_form are true, and if so, display error messages.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188202
Share on other sites

You're storing the error conditions in the $_SESSION array which is a super global (i.e. it's global with declaring it as such), so just used the session values in your other function.

 

Ken

 

I just started doing that to a few last night, but wasn't really sure if that would work.

 

Now, if I assign the session variables to regular variables like "$format_error" (for faster typing), will the variables still be global?

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188229
Share on other sites

Using $_SESSION is still an ugly way to do it.  It's actually simple to do it the right way:

 

function display_form($errors = null) // setup the function to anticipate an incoming array of errors, but have it's default value be null for those times we're SURE there can't be any errors (first time looking at the form)
{
   //...

   if ($errors != null)
   {
      // display errors
   }
}

function process_form()
{
   //...

   // if there are errors from form processing, store them in an associative array, like $errors['name'] = "Must enter in a correct name";

   display_form($errors);
}

 

There's no reason for this error data to be global, and contorting your code to make it deal with globals is the wrong way to go.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188247
Share on other sites

Using $_SESSION is still an ugly way to do it.  It's actually simple to do it the right way:

 

function display_form($errors = null) // setup the function to anticipate an incoming array of errors, but have it's default value be null for those times we're SURE there can't be any errors (first time looking at the form)
{
   //...

   if ($errors != null)
   {
      // display errors
   }
}

function process_form()
{
   //...

   // if there are errors from form processing, store them in an associative array, like $errors['name'] = "Must enter in a correct name";

   display_form($errors);
}

 

There's no reason for this error data to be global, and contorting your code to make it deal with globals is the wrong way to go.

 

Wow, that really gets rid of a lot of rather unnecessary code. And I think you're right...having all of those $_SESSION variables is really making my script crazy. Thank you =)

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188441
Share on other sites

Here's the code revised:

<?php

//****************************************
//***************Includes***************
//****************************************
require_once "arrays.php";
require_once "connect.php";
require_once "select.php";

//****************************************
//****************Action******************
//****************************************
if ($_SESSION["member"] != NULL) {
switch ($_GET["action"] {
	default:
	case "index":
		display_form();
		break;
	case "process":
		//If the submit button has been clicked...
		if (isset($nm_submit)) {
				process_form();
		} else {
			//If the user did not click the submit button
			echo "Either you have not filled out all of the information or you ended up her by mistake! Please hit the back button to start over.";
		}
		break;
}
} else {
echo "You are already a member.";
}

//****************************************
//***************Functions****************
//****************************************
//........................................
//........Function 1: display_form()......
//........................................

function display_form($nm_errors_found = NULL, $nm_error_msgs = NULL) {

global $mysql_connect;

//----------------------------------------------
//--------------Form Error Messages-------------
//----------------------------------------------
//Creates an array that holds the error messages for all possible form errors
$nm_error_msgs = array (
	"nm_field_fm_un_msg" => "*Username must start with a letter and can only contain numbers, underscores, and hyphens.", 
	"nm_field_fm_em_msg" => "*You have not entered a correct email format.",
	"nm_field_ex_un_msg" => "*This username already exists!", 
	"nm_field_ex_em_msg" => "*This email address is already in use!", 
	"nm_field_mt_pw_msg" => "*The passwords you entered do not match!", 
	"nm_field_bl_un_msg" => "*You did not enter a username!", 
	"nm_field_bl_em_msg" => "*You did not enter an email!", 
	"nm_field_bl_pw_msg" => "*You did not enter a password!", 
	"nm_field_bl_pwconf_msg" => "*You did not confirm your password!", 
	"nm_field_bl_rg_msg" => "*You did not specify a region.", 
	"nm_field_bl_cy_msg" => "*You did not select a country.", 
	"nm_field_min_nm_msg" => "*You have not entered the minimum number of characters.", 
	"nm_field_min_un_msg" => "*Your username must be at least 10 characters long.", 
	"nm_field_min_em_msg" => "*Your email must be at 10 characters long.", 
	"nm_field_min_pw_msg" => "*Your password must be at least 10 characters long.", 
	"nm_field_min_rg_msg" => "*There is no region that's less than three letters. Try again!", 
	"nm_field_max_nm_msg" => "*Your name cannot be more than 15 characters long.", 
	"nm_field_max_un_msg" => "*Your username cannot exceed 15 characters.", 
	"nm_field_max_em_msg" => "*Your email can't possibly be more than 30 characters long!", 
	"nm_field_max_pw_msg" => "*Your password must not exceed 20 characters.", 
	"nm_field_max_rg_msg" => "*There is no region on earth that's 26+ characters long!");

echo "<form name='registration_form' action='?action=process' method='post'>

<label for='name'>*Name: </label>
<input type='text' name='name' id='name' value='$nm_name'>

<label>*Birthdate: </label>";

$dates_months_select = "<select name='bd_month' id='bd_month'>";
foreach ($dates_months as $value => $label) {
	$dates_months_select .= "<option value='$value'";
		if ($nm_bd_month == $value) {
			$dates_months_select .= " SELECTED";
		}
	$dates_months_select .= ">$label</option>";
}
$dates_months_select .= "</select>";
echo $dates_months_select;

$dates_days_select = "<select name='bd_day' id='bd_day'>";
foreach ($dates_days as $value => $label) {
	$dates_days_select .= "<option value='$value'";
		if ($nm_bd_day == $value) {
			$dates_months_select .= " SELECTED";
		}
	$dates_days_select .= ">$label</option>";
}
$dates_days_select .= "</select>";
echo $dates_days_select;

$dates_years_select = "<select name='bd_year' id='bd_year'>";
foreach ($dates_years as $value => $label) {
	$dates_years_select .= "<option value='$value'";
		if ($nm_bd_year == $value) {
			$dates_years_select .= " SELECTED";
		}
	$dates_years_select .= ">$label</option>";
}
$dates_years_select .= "</select>";
echo $dates_years_select;

echo "<label for='country'>*Country: </label>";

$regions_countries_select = "<select name='country' id='country'>";
foreach ($regions_countries as $value => $label) {
	$regions_countries_select .= "<option value='$value'";
		if ($nm_country == $value) {
			$regions_countries_select .= " SELECTED";
		}
	$regions_countries_select .= ">$label</option>";
}
$regions_countries_select .= "</select>";
echo $regions_countries_select;

echo "<label for='region'>*State/Region: </label>
<input type='text' name='region' id='region' value='$nm_region'>

<label for='gender'>*Gender: </label>
<label>Male</label>
<input type='radio' name='gender' id='gender_male' ";

if ($nm_gender == "Male") { 
	echo "SELECTED >"; 
} 

echo "<label>Female</label>
<input type='radio' name='gender' id='gender_female' ";

if ($nm_gender == "Female") { 
	echo "SELECTED >"; 
}

echo "<label for='website'>Website: </label>
<input type='text' name='website' id='website' value='$nm_website'>

<label for='email'>Email: </label>
<input type='text' name='email' id='email' value='$nm_email'>";
if ($nm_field_fm_em) { echo $nm_field_fm_em_msg; }
if ($nm_field_ex_em) { echo $nm_field_ex_em_msg; }

echo "<label for='username'>Username: </label>
<input type='text' name='username' id='username' value='$nm_username'>";
if ($nm_field_fm_un) { echo $nm_field_fm_un_msg; } 
if ($nm_field_ex_un) { echo $nm_field_ex_un_msg; }

echo "<label for='password'>Password: </label>
<input type='password' name='password' id='password'>";
if ($nm_field_mt_pw) { echo $nm_field_mt_pw_msg; }

echo "<label for='password_confirm'>Confirm Password: </label>
<input type='password' name='password_confirm' id='password_confirm'>";
if ($nm_field_mt_pw) { echo $nm_field_mt_pw_msg; }

echo "<input type='check' name='newsletter' id='newsletter' CHECKED>
<label for='newsletter'>Sign me up for the newsletter!</label>

<input type='check' name='tos' id='tos'>
<label for='tos'>I agree to the terms of service.</label>
<input type='hidden' name='date' id='date' value='";

echo date('F d, Y') . "'>";

echo "<input type='hidden' name='time' id='time' value='"; 

echo date('g:I:sa') . "'>";

echo "<input type='submit' name='submit' id='submit'>

<input type='reset' name='reset' id='reset'>
</form>";

}
    
//........................................
//........Function 2: process_form()......
//........................................

function process_form() {

global $mysql_connect;

//**************************************
//***********Error Trapping*************
//**************************************
//******(...in the event that the ******
//**********user does not have********** 
//********javascript enabled...)********
//----------------------------------------------
//------------------Form Errors-----------------
//----------------------------------------------
//Create an array that stores possible form errors
$nm_errors = array (
"nm_field_fm_un" => NULL, 
"nm_field_fm_em" => NULL, 
"nm_field_ex_un" => NULL, 
"nm_field_ex_em" => NULL, 
"nm_field_mt_pw" => NULL, 
"nm_field_bl_un" => NULL, 
"nm_field_bl_em" => NULL, 
"nm_field_bl_pw" => NULL, 
"nm_field_bl_pwconf" => NULL, 
"nm_field_bl_rg" => NULL, 
"nm_field_bl_cy" => NULL, 
"nm_field_bl_bdm" => NULL, 
"nm_field_bl_bdd" => NULL, 
"nm_field_bl_bdy" => NULL, 
"nm_field_min_nm" => NULL, 
"nm_field_min_un" => NULL, 
"nm_field_min_em" => NULL, 
"nm_field_min_pw" => NULL, 
"nm_field_min_rg" => NULL, 
"nm_field_max_nm" => NULL, 
"nm_field_max_un" => NULL, 
"nm_field_max_em" => NULL, 
"nm_field_max_pw" => NULL, 
"nm_field_max_rg" => NULL, 
);

//----------------------------------------------
//---------------Testing Form Input-------------
//----------------------------------------------
//Check Email Format
if(!ereg("^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$", $nm_email)) {
	$nm_errors_found = true;
	$nm_errors["nm_field_fm_em"] = true;
}

//Check Username Format
if(!ereg("^[[:alpha:]](\_)*(\-)*([a-z0-9-A-Z])*", $nm_username)) {
	$nm_errors_found = true;
	$nm_errors["nm_field_fm_un"] = true;
}

//Check To See If Email Already Exists
$email_check = mysql_query("SELECT email FROM fans WHERE email = '$nm_email'"); 
$do_email_check = mysql_num_rows($email_check);
if ($do_email_check > 0) {
	$nm_errors_found = true;
	$nm_errors["nm_field_ex_em"] = true;
}

//Check To See If Username Already Exists
$username_check = mysql_query("SELECT username FROM fans WHERE username = '$nm_username'"); 
$do_username_check = mysql_num_rows($username_check);
if ($do_username_check > 0) {
	$nm_errors_found = true;
	$nm_errors["nm_field_ex_un"] = true;
}

//Check Email Field
if (!isset($nm_email) || !$nm_email || $nm_email == 0 || $nm_email == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_em"] = true;
}

//Check Username Field
if (!isset($nm_username) || !$nm_username || $nm_username == 0 || $nm_username == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_un"] = true;
}

//Check Password Field
if (!isset($nm_password) || !$nm_password || $nm_password == 0 || $nm_password == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_pw"] = true;
}

//Check Password (Confirm) Field
if (!isset($nm_passwordconfirm) || !$nm_passwordconfirm || $nm_password == 0 || $nm_passwordconfirm == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_pwconf"] = true;
}

//Check Birthdate Fields
if (!isset($nm_bd_month) || !$nm_bd_month || $nm_bd_month == 0 || $nm_bd_month == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_bdm"] = true;
}
if (!isset($nm_bd_day) || !$nm_bd_day || $nm_bd_day == 0 || $nm_bd_day == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_bdd"] = true;
}
if (!isset($nm_bd_year) || !$nm_bd_year || $nm_bd_year == 0 || $nm_bd_year == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_bdy"] = true;
}

//Check Region Field
if (!isset($nm_region) || !$nm_region || $nm_region == 0 || $nm_region == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_rg"] = true;
}

//Check Country Field
if (!isset($nm_country) || !$nm_country || $nm_country == 0 || $nm_country == false) {
	$nm_errors_found = true;
	$nm_errors["nm_field_bl_cy"] = true;
}	

//Check To See If Both Passwords Match
if (isset ($nm_password) && isset ($nm_passwordconfirm) {
	if ($nm_password  != $nm_passwordconfirm) {
		$nm_errors_found = true;
		$nm_errors["nm_field_mt_pw"] = true;
	}
}

//Check to see if name is at least 5 characters long
if (strlen ($nm_name) < 5) {
	$nm_errors_found = true;
	$nm_errors["nm_field_min_nm"] = true;
}

//Check to see if username is at least 5 characters long
if (strlen ($nm_username) < 5) {
	$nm_errors_found = true;
	$nm_errors["nm_field_min_un"] = true;
}

//Check to see if email is at least 10 characters long
if (strlen ($nm_email) < 10) {
	$nm_errors_found = true;
	$nm_errors["nm_field_min_em"] = true;
}

//Check to see if password is at least 10 characters long
if (strlen ($nm_password) < 10) {
	$nm_errors_found = true;
	$nm_errors["nm_field_min_pw"] = true;
}

//Check to see if region is at least 3 characters long
if (strlen ($nm_region) < 3) {
	$nm_errors_found = true;
	$nm_errors["nm_field_min_rg"] = true;
}

	//Check to see if name is more than 15 characters
if (strlen ($nm_name) > 15) {
	$nm_errors_found = true;
	$nm_errors["nm_field_max_nm"] = true;
}

//Check to see if username is more than 20 characters
if (strlen ($nm_username) > 20) {
	$nm_errors_found = true;
	$nm_errors["nm_field_max_un"] = true;
}

//Check to see if email is more than 30 characters
if (strlen ($nm_email) > 30) {
	$nm_errors_found = true;
	$nm_errors["nm_field_max_em"] = true;
}

//Check to see if password is more than 20 characters
if (strlen ($nm_password) > 20) {
	$nm_errors_found = true;
	$nm_errors["nm_field_max_pw"] = true;
}

//Check to see if region is more than 25 characters
if (strlen ($nm_region) > 25) {
	$nm_errors_found = true;
	$nm_errors["nm_field_max_rg"] = true;
}

//**************************************
//**************Variables***************
//**************************************
//-----------------------------------------
//--------------Form Elements--------------
//-----------------------------------------
//The variables below require the following special formatting:
//"Strips" any slashes from values, converts html tags into ascii characters, prevents mysql injection...
//The $_POST values then get assigned to $_SESSION variables
$_SESSION["nm_name"] = htmlentities (stripslashes (mysql_real_escape_string ($_POST["name"])));
$_SESSION["nm_region"] = htmlentities (stripslashes (mysql_real_escape_string ($_POST["region"])));
$_SESSION["nm_website"] = htmlentities (stripslashes (mysql_real_escape_string ($_POST["website"])));
$_SESSION["nm_email"] = htmlentites (stripslashes (mysql_real_escape_string ($_POST["email"])));
$_SESSION["nm_username"] = htmlentities (stripslashes (mysql_real_escape_string ($_POST["username"])));
$_SESSION["nm_password"] = htmlentities (stripslashes (mysql_real_escape_string ($_POST["password"])));
//Assigns the above $_SESSION variables to regular variables
$nm_name = $_SESSION["nm_name"];
$nm_region = $_SESSION["nm_region"];
$nm_website = $_SESSION["nm_website"];
$nm_email = $_SESSION["nm_email"];
$nm_username = $_SESSION["nm_username"];
$nm_password = $_SESSION["nm_password"];

//Drop-downs, radio groups, check boxes, and submit buttons
//These items do not need special formatting (e.g., stripslashes, mysql_real_escape_string, etc.)
//Assigns $_POST values to $_SESSION variables
$_SESSION["nm_country"] = $_POST["country"];
$_SESSION["nm_gender"] = $_POST["gender"];
$_SESSION["nm_bd_month"] = $_POST["bd_month"];
$_SESSION["nm_bd_day"] = $_POST["bd_day"];
$_SESSION["nm_bd_year"] = $_POST["bd_year"];
$_SESSION["nm_subscribe"] = $_POST["newsletter"];
//Assigns the above $_SESSION variable to regular variables
$nm_country = $_SESSION["nm_country"];
$nm_gender = $_SESSION["nm_gender"];
$nm_bd_month = $_SESSION["nm_bd_month"];
$nm_bd_day = $_SESSION["nm_bd_day"];
$nm_bd_year = $_SESSION["nm_bd_year"];
$nm_subscribe = $_SESSION["nm_subscribe"];

//These items do not need to be assigned to $_SESSION variables, as they will not be "echoed" in the form's "value" attribute, 
//and are dynamically generated each time the form is submitted
$nm_passwordconfirm = $_POST["password_confirm"];
$nm_date = $_POST["date"];
$nm_time = $_POST["time"];
$nm_birthdate = $nm_bd_month . " " . $nm_bd_day . ", " . $nm_bd_year;
$age = $current_year - $nm_bd_year;
$nm_submit = $_POST["submit"];
$nm_tos = $_POST["tos"];

//------------------------------------------
//--------------Miscellaneous---------------
//------------------------------------------
//Get current year
$current_year = echo date('Y');

//**************************************
//***************Action*****************
//**************************************
//If errors were found, show login form w/errors
if ($nm_errors_found) {
	display_form($nm_errors);
//If no errors were found...
} else {
	//Register member
	mysql_query(INSERT INTO fans (id, name, birthdate, country, region, gender, website, email, username, password, date_registered, time_registered, age) VALUES ("", $nm_name, $nm_birthdate, $nm_country, $nm_region, $nm_gender, $nm_website, $nm_email, $nm_username, $nm_password, $nm_date, $nm_time, $nm_age));

	//If member clicked the "subscribe to newsletter" box, add member to table "subscribers"
	if (isset($nm_subscribe)) {
		mysql_query(INSERT INTO fans_subscribers (username, email) VALUES ($nm_username, $nm_email));
	}

	//Insert member into "offline" table; member remains in this table until he/she logs in for the first time
	mysql_query(INSERT INTO fans_offline (username) VALUES ($nm_username));

	//Close connection
	mysql_close;

	//Display "welcome" message
	echo "Welcome, $nm_username! You may now proceed <A HREF=\"../login.php\">here</A> to login.";

	//Empty and destry the $_SESSION
	$_SESSION = array ();
	session_destroy ();
}
}

?>

 

So, I created an array of all possible form errors and set them all to "NULL". Then, when the script goes through to check the fields, it'll set the necessary variables from that array to true. If any errors were found, it would then execute "display_form()" with that entire array of variables passed through the argument parameter. Then, the if statements in the form can check to see which fields have encountered an error, and decide to display a message.  I realize I haven't put all the necessary if statements in my "display_form()" function yet...

 

So, am I on the right track? Does this script do what it's supposed to do lol?

 

 

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188491
Share on other sites

Close.  If you're creating an array within a function, it doesn't (and shouldn't) be listed in its argument list.  A function's argument list is like a bouncer at a bar - it expects certain guests.  If a guest is already in the bar, it doesn't need to be on the bouncer's list.

 

See more at (examples 3 and 4): http://php.net/manual/en/functions.arguments.php

 

Also, stop using global!.  Pass in ALL of the necessary data necessary to execute your functions.  This includes your db connection.  I don't know where you learned to use global - a book, an instructor, whatever - but it's a real bad habit to get into.  You're only hurting yourself when you use it.  Here's why:

 

Functions have a signature, which is both their identification and a summary of what they are.  It consists of three parts - the function's return value type, the function's name, and the type and number of the arguments the function expects to receive in order for it all to work.  The signature literally says "Function function name will return a value of type type when n arguments of the following types (types) are passed into it."

 

PHP glosses over this a bit because it's dynamically typed, so many coders - especially newbies - don't really have a grasp on what type is.  That doesn't mean it doesn't exist, or isn't important.  Other, statically typed languages make it much more clear.  It's not uncommon to see something like:

 

bool IsEqual(string str1, string str2)
{
   // ...
}

 

Which says "The IsEqual function returns a boolean and requires two strings to be passed in."

 

When you use 'global' you do a few things: you muddy the function's signature, you introduce a hidden requirement to the function, and the function makes an assumption about the environment in which it's executed.  In short, you couple (tie together) the function to the environment in which it's called, which negates the entire point of functions.  Functions are supposed to be modular.  Their requirements are explicit, and known ahead of time.

 

Even if you never work with someone else's code (which, if you're going to do this for more than a hobby, you will at some point), your own coding life is made worse by using 'global'.  When trying to debug your code, you'll be required to look into the guts of your function(s), then at the context in which it was called in order to see if the environment was set just right.  You'll have to scan your code line-by-line to see if the environment variable exists at all, or has the right type (there's that word again) of value.  And what about nested functions?  This thread highlights some of the issues there.

 

It's normally around this point that two counter arguments pop up:

 

1. Popular PHP software X uses 'global' in its code!

2. If 'global' is so bad, why is it in the language?

 

1. An app's popularity speaks nothing about its craftsmanship.  Wordpress is probably the most popular blogging software on the planet, but it's a steaming pile under the hood.

 

2. Many questionable constructs exist in many languages.  They're often remnants of an earlier time, when modern best practices weren't known.  Look at 'goto': it's widely considered a four letter word.  It leads to spaghetti code (not unlike 'global'), and with modern control structures and design techniques, is hardly ever necessary.  At my university, a student would automatically fail if they used it.  Just because a language provides you with something, that doesn't mean it's wise or even necessary to use it.  There are better ways.

 

Sorry about the rant, but I see this sort of thing all the time on here, and I have no idea where it comes from.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188620
Share on other sites

Close.  If you're creating an array within a function, it doesn't (and shouldn't) be listed in its argument list.  A function's argument list is like a bouncer at a bar - it expects certain guests.  If a guest is already in the bar, it doesn't need to be on the bouncer's list.

 

I appreciate the long reply, but I'm still not understanding. I understand, now, that using global is a no-no and that arrays shouldn't be passed through an argument parameter in a function...so how do I get the values of the $error array (the one that holds "true" values if a form has been caught as invalid) sent to the other function?

 

What I'm not sure of is, is whether or not I need to get those array values sent to the other function, or if I can just leave it how it is, because the function that requires those values gets called within the function that already contains the values?

 

And I remember either you or someone else said earlier I had to pass a variable through the argument parameter of display_form();...what variable should I be passing over, if any?

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188921
Share on other sites

Please re-read what I wrote and be sure to also read the examples I linked to.  I never said that arrays shouldn't be used as parameters.  In fact, I explicitly wrote code showing that they could, which, in turn, is the way I'd go about solving your problem.  What I actually said is that if you're creating an array for use in a function WITHIN that same function that's going to be using it (like what you do in display_fotm where you create your error message array), then you don't need to list it in the function's argument list.  Why?  Because it's already there.  You just created it.

 

You should do some research on scope (a Google search along the lines of "PHP function scope" or "PHP block scope" should do the trick) and really brush up on functions.  Not just their syntax, but what they are, why we use them, and why they should be made as abstract as possible.  I'm getting the feeling that you're lacking some fundamental knowledge, and you're going to keep running into problems if you continue this way.  It's difficult to efficiently teach this on a forum.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1188998
Share on other sites

I have a PHP reference manual, and I've read a lot on functions and "global scope". I already knew that in order to make variables global within a function, you use the global function, and I think there's something about "variable scope", which is local or relative. I also know that variables that begin with an underscore are always global and don't need to be defined as global. I think they're called superglobals?

 

I understand the whole argument thing much better now; same with the array deal. Passing an array as a parameter through a function, though, is still confusing; I'm having difficulty imagining what could be done by doing such a thing. But I definitely understand what you mean about this:

 

Please re-read what I wrote and be sure to also read the examples I linked to.  I never said that arrays shouldn't be used as parameters.  In fact, I explicitly wrote code showing that they could, which, in turn, is the way I'd go about solving your problem.  What I actually said is that if you're creating an array for use in a function WITHIN that same function that's going to be using it (like what you do in display_fotm where you create your error message array), then you don't need to list it in the function's argument list.  Why?  Because it's already there.  You just created it.

 

So, if I place any variables need by a function within those functions, my code should be okay?

 

The reason I ask rather than debug the code on my host server, is because I want to make sure it works before I launch it (can't use wamp or xamp cuz my computer's really slow).

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1189211
Share on other sites

I have a PHP reference manual, and I've read a lot on functions and "global scope". I already knew that in order to make variables global within a function, you use the global function, and I think there's something about "variable scope", which is local or relative.

 

Global scope is considered dangerous due to how easy it is to corrupt the values of a 'global' variable.  There's no built-in check to see if a global has been changed, deleted, or even exists at all.  Like I said earlier, 'global' tightly couples your functions to the global environment in which they're invoked.  Any changes made to the global variable can spider throughout your code, often in ways you don't expect.

 

Since PHP doesn't have a true global scope, functions have two ways to obtain variables from outside of them - by using the 'global' keyword, which simulates normal global behavior, or by passing them in through the argument list, which, by default, sends a copy of the variable to the function to play with.  This is the preferred way to do it.

 

Keep in mind, globals are considered dangerous regardless of language.  It's one of the reasons why namespaces exist, and have been introduced in the most recent version of PHP.  They're limiting, they lead to badly written code, and they cause problems by their very existence.

 

I also know that variables that begin with an underscore are always global and don't need to be defined as global. I think they're called superglobals?

 

This isn't entirely true.  PHP has several pre-defined superglobal arrays, like $_GET, $_POST, and $_SESSION.  You can't make your own superglobal, so if you try something like: $_PUPPIES, you'll simply be making a normal variable.

 

Superglobals aren't ideal, but are a reasonable compromise since they're often used in a read-only manner, or used to persist data between HTTP requests.  HTTP's request cycle makes them necessary.

 

I understand the whole argument thing much better now; same with the array deal. Passing an array as a parameter through a function, though, is still confusing; I'm having difficulty imagining what could be done by doing such a thing.

 

It's actually used quite often in frameworks when you need to pass an unknown number of values (think config settings) to a function.

 

But I definitely understand what you mean about this:

 

Please re-read what I wrote and be sure to also read the examples I linked to.  I never said that arrays shouldn't be used as parameters.  In fact, I explicitly wrote code showing that they could, which, in turn, is the way I'd go about solving your problem.  What I actually said is that if you're creating an array for use in a function WITHIN that same function that's going to be using it (like what you do in display_fotm where you create your error message array), then you don't need to list it in the function's argument list.  Why?  Because it's already there.  You just created it.

 

So, if I place any variables need by a function within those functions, my code should be okay?

 

The reason I ask rather than debug the code on my host server, is because I want to make sure it works before I launch it (can't use wamp or xamp cuz my computer's really slow).

 

So, to try to explain it another way, your current concern is "Where does the data that makes the function work come from?"  In your case, from two places:

 

1. Outside the function.  The errors you generate in process_form ($nm_errors) need to be sent to display_form.  Since display_form needs the errors, and they're generated by an outside source, the only way display_form can get them is if they're passed in through display_form's argument list.

 

2. Inside the function itself.  The error messages ($nm_error_messages) are created inside of display_form.  Because of this, you don't need to add it to the argument list.  It's already taken care of.

 

Remember my analogy - the argument list acts like a bouncer.  Only the people on the list go into the bar.  If a person is already in the bar, they're crossed off the list.  $nm_errors is a person waiting outside the bar.  $nm_error_messages is already in the bar, so they're not on the list.

 

And, for a general rule of thumb: where you'd use 'global', use the argument list instead.

 

I hope this makes sense.  I know I can be long-winded, but I really want you (and others) to understand what's actually going on.  I've seen far too many cases where someone was told "Do X instead of Y," only for them to be frustrated when X doesn't work every time and they don't understand why.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1189226
Share on other sites

Nope. According to the PHP Manual entry on variables:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1189402
Share on other sites

Nope. According to the PHP Manual entry on variables:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

 

Ken

 

Wowwwwwwwww, my book really sucks. I got this stupid reference manual at Borders and it says variables starting with underscores are invalid. WTF

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1189403
Share on other sites

Nope. According to the PHP Manual entry on variables:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

 

Ken

 

Wowwwwwwwww, my book really sucks. I got this stupid reference manual at Borders and it says variables starting with underscores are invalid. WTF

 

When in doubt, consult the actual language manual: http://www.php.net/manual/en/langref.php

 

And having an underscore as the leading character of a variable is used a lot in OOP.  They're often used to denote private fields in an effort to increase readability.

Link to comment
https://forums.phpfreaks.com/topic/230762-function-variables/#findComment-1189478
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.