PHP Functions and Variable Scope
In this handout you will learn how to use and create functions in PHP.
Handling Checkboxes
HTML forms often contain checkboxes. Checkboxes require a bit of special processing in the PHP code that receives the form data.
The Checkbox Demo has an HTML page with a form in it, and a separate PHP action page that processes the form data.
The code for the Checkbox Demo is shown below. The first page is checkDemoForm.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Checkbox Demo</title>
</head>
<body>
<div id="mainDiv">
<h1>Checkbox Demo</h1>
<h3>Demonstrates checkboxes</h3>
<form action = "checkDemoAction.php" method="post">
<h3>What would you like with your order?</h3>
<ul>
<li><input type = "checkbox"
name = "chkFries"
value = "1.00">Fries
</li>
<li><input type = "checkbox"
name = "chkSoda"
value = ".85">Soda
</li>
<li><input type = "checkbox"
name = "chkShake"
value = "1.30">Shake
</li>
<li><input type = "checkbox"
name = "chkKetchup"
value = ".05">Ketchup
</li>
</ul>
<input type = "submit" value="Place your order">
</form>
</div>
</body>
</html>
The second page is checkDemoAction.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Checkbox Demo</title>
</head>
<body>
<div id="mainDiv">
<h1>Checkbox Demo</h1>
<h3>Demonstrates reading checkboxes</h3>
<?php
if (isset($_POST["chkFries"]))
{
$item1Cost = $_POST["chkFries"];
}
else
{
$item1Cost = "";
}
if (isset($_POST["chkSoda"]))
{
$item2Cost = $_POST["chkSoda"];
}
else
{
$item2Cost = "";
}
if (isset($_POST["chkShake"]))
{
$item3Cost = $_POST["chkShake"];
}
else
{
$item3Cost = "";
}
if (isset($_POST["chkKetchup"]))
{
$item4Cost = $_POST["chkKetchup"];
}
else
{
$item4Cost = "";
}
$total = 0;
if ($item1Cost != "")
{
print ("You chose Fries<br>");
$total = $total + $item1Cost;
}
if ($item2Cost != "")
{
print ("You chose Soda<br>");
$total = $total + $item2Cost;
}
if ($item3Cost != "")
{
print ("You chose a Shake<br>");
$total = $total + $item3Cost;
}
if ($item4Cost != "")
{
print ("You chose Ketchup<br>");
$total = $total + $item4Cost;
}
print ("<br>The total cost is \$$total");
?>
</div>
</body>
</html>
Please note these points about the above Checkbox Demo code:
-
If a checkbox is checked, its value attribute's value
will be sent to the form processing (action) page.
- If a checkbox is not checked, nothing will be sent to the form processing page for that checkbox. We use the built-in function isset( ) to test whether the variable was sent to the page.
The printf( ) Function
You may have noticed that the "total" number in the previous section's sample page does not always look very pretty. For instance,
The total cost is $0.9does not look normal. We are used to seeing
The total cost is $0.90
PHP has a built-in function, printf( ), which allows you to control the formatting and display of numbers such as the dollar totals in the sample above.
The syntax of printf( ) is like this:
printf (<format> [,argument [,argument [,...]]]);
where <format> is a string which can contain normal text and some special formatting characters, or just formatting characters; and [,argument [,... is/are the item(s) that you want to format.
For example, in the sample code above, we could put this line of code in place of the current "total" line:
printf("<br />The total cost is \$%01.2f", $total);
Please note these points about the format string above:
-
The part that looks like
%01.2f
tells PHP to format the number (in the variable $total, in this case) as a "floating point number with 2 decimal places and at least one number in front of the decimal point".
-
The part that looks like
\$
tells PHP to put a literal dollar-sign ($) character into the string. If you did not put the backslash (\) immediately before the dollar-sign, PHP would look for a variable to interpolate (to put its value into the string).
A more detailed description of the available format characters is at http://www.php.net/manual/en/function.sprintf.php which is specifically in the section for sprintf( ), but printf( ) uses the same formatting characters. Make sure you scroll down to the many examples, also.
Creating Custom Functions
When your PHP code pages get longer and more involved, you will probably need to break up the code into manageable chunks. One way to do this breaking up is to make your own functions.
The This Old Man Page shows how to make and use your own functions.
And as a reminder, a function is a named group of code which does something. A function often returns a value to the place in your code where the function is called/run from.
The code for the This Old Man Page is shown below. This is page thisOldMan.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>This Old Man</title>
</head>
<body>
<div id="mainDiv">
<h1>This Old Man</h1>
<h3>Demonstrates use of functions</h3>
<?php
verse1();
chorus();
verse2();
chorus();
function verse1(){
print <<<HERE
This old man, he played 1<br />
He played knick-knack on my thumb<br /><br />
HERE;
} // end verse1
function verse2(){
print <<<HERE
This old man, he played 2<br />
He played knick-knack on my shoe<br /><br />
HERE;
} // end verse1
function chorus(){
print <<<HERE
...with a knick-knack<br />
paddy-whack<br />
give a dog a bone<br />
this old man came rolling home<br />
<br /><br />
HERE;
} // end chorus
?>
</div>
</body>
</html>
Please note these points about the above This Old Man Page's code:
-
You start creating your own function with the function keyword.
-
Then you name your function, and follow the name with a set of
parentheses.
-
You put the function's group of code inside a set of curly braces.
-
You run, or call, your function by putting the function's name( )
in your code, followed of course by a semi-colon.
-
There are three custom functions in the above code. They are named
- verse1()
- verse2()
- chorus()
- The function chorus() is called twice. This kind of re-use of the same function is, in fact, one of the main advantages of using functions in the first place.
Functions with Parameters
Functions are meant to be self-contained. If your function needs any information from elsewhere in the page, the best way to provide the data and information that your function needs is to use parameters.
Please note these points about using parameters:
-
A potential point of confusion about parameters
is that the information that is sent into a function is called an argument (or some arguments)
when you use (call) the function. The same
information is called a parameter (or some
parameters) from the function's perspective, meaning inside the function
code that
you write. So an argument's value becomes
(in the function itself) a parameter's value. The terminology is a matter
of perspective.
- If you need to send any information from your function back to where the function was called from, it is best to return a value.
The Param Old Man Page shows how to use parameters and a return in your functions.
The code for the Param Old Man Page is shown below. This is page param.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Param Old Man</title>
</head>
<body>
<div id="mainDiv">
<h1>Param Old Man </h1>
<h3>Demonstrates use of function parameters</h3>
<?php
print verse(1);
print chorus();
print verse(2);
print chorus();
print verse(3);
print chorus();
print verse(4);
print chorus();
function verse($stanza){
switch ($stanza){
case 1:
$place = "thumb";
break;
case 2:
$place = "shoe";
break;
case 3:
$place = "knee";
break;
case 4:
$place = "door";
break;
default:
$place = "I don't know where";
} // end switch
$output = <<<HERE
This old man, he played $stanza<br>
He played knick-knack on my $place<br><br>
HERE;
return $output;
} // end verse
function chorus(){
$output = <<<HERE
...with a knick-knack<br>
paddy-whack<br>
give a dog a bone<br>
this old man came rolling home<br>
<br><br>
HERE;
return $output;
} // end chorus
?>
</div>
</body>
</html>
Please note these points about the above Param Old Man Page's code:
-
The main part of the code page now uses the
print( )
built-in function
to call each custom (your own) function.
- The term "built-in" means that the function is part of the PHP language itself.
- The term "custom" means that the function is written by you, and is not part of the PHP language itself. Of course, your custom function uses the PHP language in its statements!
-
A value is sent back to where each function is called, by using the return
keyword followed by whatever needs to be returned.
-
The
print( )
function in each line is putting the value that is returned from each custom function,
into the
page.
-
Each of the custom functions creates a variable called $output. But
the variable in each custom function is an entirely separate variable
from the one in the other function. They just happen to be named the same in
this page's code, to make the point that a variable created inside a
function exists only inside that function and loses its meaning and its value
once the function is done running.
-
The custom function verse( ) uses a parameter that is called
$stanza. A parameter is essentially another kind of variable
that is useful only inside the function that it belongs to.
-
This particular code does not use multiple parameters, but a function
may do so if needed. You separate multiple parameters with commas.
- When the function verse( ) is called, a value is sent to the function by putting something inside the parentheses. This value is called an argument and it becomes the parameter (variable) that is used inside the function.
A Second Parameter Example
Here is a second example of how to use parameters in a custom function. Recall that by "custom function", I mean one that you define (write) in your PHP page.
In this second example I will show how to use these features of PHP:
- Multiple parameters
- String values as parameters
- Boolean values as parameters
You can see the second example pages running here.
The HTML form page is SecondExample.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Custom Function Demo</title>
</head>
<body>
<div id="mainDiv">
<h1>Custom Function Demo</h1>
<form action = "SecondExample.php" method="post">
<h3>Please choose your favorite color</h3>
<ul>
<li><input type = "radio"
name = "favColor"
value = "red"> red
</li>
<li><input type = "radio"
name = "favColor"
value = "orange"> orange
</li>
<li><input type = "radio"
name = "favColor"
value = "yellow"> yellow
</li>
<li><input type = "radio"
name = "favColor"
value = "green"> green
</li>
<li><input type = "radio"
name = "favColor"
value = "blue"> blue
</li>
<li><input type = "radio"
name = "favColor"
value = "indigo"> indigo
</li>
<li><input type = "radio"
name = "favColor"
value = "violet"> violet
</li>
</ul>
<input type = "submit" value="Next >>">
</form>
</div>
</body>
</html>
The form's action page is SecondExample.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Custom Function Demo</title>
</head>
<body>
<div id="mainDiv">
<h1>Custom Function Demo</h1>
<?php
function displayColorInfo($itemInfo, $addColorBox)
{
if (isset($_POST[$itemInfo]))
{
$colorValue = $_POST[$itemInfo];
}
else
{
$colorValue = "Not picked";
}
if ($colorValue != "Not picked")
{
print "You chose ";
print $colorValue;
print "<br>";
if ($addColorBox)
{
print "<div style='width:40px; height:40px; background-color:$colorValue;'> </div>";
}
}
else
{
print "It would be nice if you would pick a color! Please go back!";
}
}
print "<h3>This section will NOT show the color box</h3>";
displayColorInfo("favColor", False);
print "<br><br>";
print "<h3>This section will show the color box</h3>";
displayColorInfo("favColor", True);
?>
</div>
</body>
</html>
Please note these points about the above code:
-
The first parameter that the custom function receives contains a string
value. It contains the name of the radio buttons on the HTML form.
-
The second parameter that the custom function receives contains a boolean
value. It is a "flag" that tells the function whether or not to display
a box with the background color that the user chose on the HTML form.
-
This statement:
if ($addColorBox)
uses shorthand notation to test for the boolean value in the $addColorBox parameter. It is completely and totally equivalent to this statement:if ($addColorBox == True)
and you can use either syntax, depending on which syntax you prefer.
- The <div> tag which displays the background color, is placed into the page with a double-quoted string. The double quotes allow the statement to use variable interpolation to put the color value into the inline stylesheet.
Variable Scope
A variable that is created outside a function is a global variable. This term means that the variable can be used anywhere in the page.
But if you need to use a global variable inside a function, you must explicitly tell PHP that the variable is global. If you do not, PHP will treat the variable as a variable that is local only to that function. This feature is designed into PHP. It is not a bug. Seriously.
The Scope Demo Page shows how to use a global variable inside a custom function.
The code for the Scope Demo Page is shown below. This is page scope.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Scope Demo</title>
</head>
<body>
<div id="mainDiv">
<h1>Scope Demo</h1>
<h3>Demonstrates variable scope</h3>
<?php
$a = "I have a value";
$b = "I have a value";
print <<<HERE
outside the function, <br>
\$a is "$a", and<br>
\$b is "$b"<br><br>
HERE;
myFunction();
function myFunction(){
//make $a global, but not $b
global $a;
print <<<HERE
inside the function, <br>
\$a is "$a", and<br>
\$b is "$b"<br><br>
HERE;
} // end myFunction
?>
</div>
</body>
</html>
Please note these points about the above Scope Demo Page's code:
-
The variable $b is not defined inside the function myFunction(). Of course,
this is not good programming practice. I did it this way in this code to make
a point. And if the PHP processor has error messages
turned on for undefined variables, you may see a message like
this:
Notice: Undefined variable: b in F:\web\imed2351n01\PHPStuff\scope.php on line 30
-
To tell your custom function that a variable that is being used is global,
you use the global keyword followed by the name of the variable.
- If you want to print the dollar sign, you need to precede it with a backslash. The backslash tells PHP to actually put the following character into the page, instead of looking for a variable name after the dollar sign.
A Better Way
Even though you can use global variables in a function, as shown in the previous section, many philosophers of programming say that it is better practice to send the global information into the function via parameters. The following revision of the previous sample code shows how this use of parameters might look.
This is page globalDemo.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Scope Demo</title>
</head>
<body>
<div id="mainDiv">
<h1>Scope Demo</h1>
<h3>Demonstrates variable scope</h3>
<?php
$a = "I have a value";
$b = "I have another value";
print <<<HERE
outside the function, <br>
\$a is "$a", and<br>
\$b is "$b"<br><br>
HERE;
function myFunction($aardvark, $elephant){
$myStuff = <<<HERE
inside the function, <br>
\$aardvark is "$aardvark", and<br>
\$elephant is "$elephant"<br><br>
HERE;
return $myStuff;
} // end myFunction
print myFunction($a, $b);
?>
</div>
</body>
</html>
Please note these points about the revised code:
-
The function myFunction() now has two parameters.
-
When myFunction() is called (in the print statement at the bottom
of the page), the two global variables $a
and $b are sent into the function via the function's two
parameters.
-
Inside the function, the two parameters are used like any other
local variables in a function.
-
The parameter names are silly on purpose. I am making that point that
you can name your functions whatever you want to. But please keep in
mind that in the real world, it is better to name your parameters so that
you can more easily tell what kind of information is in the parameter's
value, or at least more easily distinguish which parameter you are using
in the function's code. So in the real world, these parameters would be better named
as something like $firstParameter and secondParameter, or
whatever helps you to keep track of the values in your code.
-
The function creates a variable, $myStuff, whose
value is returned to the place
where the function was called from.
- The function's return value is put into the page in the statement which calls the print function.