Home arrow PHP arrow Page 8 - The PHP Scripting Language

User-Defined Functions - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article



User-defined functions provide a way to group together related statements into a cohesive block. For reusable code, a function saves duplicating statements and makes maintenance of the code easier. Consider an example of a simple user-developed function as shown in Example 2-3.

Example 2-3. A user-defined function to output bold text

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     "http://www.w3.org/TR/html401/loose.dtd"> <html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Function Call</title> </head>
<body bgcolor="#ffffff">
function bold($string)
    print "<b>" . $string . "</b>";
// First example function call (with a static string)
print "this is not bold ";
bold("this is bold ");
print "this is again not bold ";
// Second example function call (with a variable)
$myString = "this is bold";

The script defines the function bold( ), which takes one parameter,$string, and prints that string prefixed by a bold<b>tag and suffixed with a</b>tag. The parameter$stringis a variable that is available in the body of the function, and the value of$stringis set when the function is called. As shown in the example, the function can be called with a string literal expression or a variable as the parameter.

Functions can also return values. For example, consider the following code fragment that declares and uses a function heading( ), which returns a string using thereturnstatement:

function heading($text, $headingLevel)
   switch ($headingLevel)
   case 1:
$result = "<h1>$text</h1>";
case 2:
       $result = "<h2>$text</h2>";
case 3:
       $result = "<h3>$text</h3>";
$result = "<p><b>$text</b></p>";
$test = "User-defined Functions";
print heading($test, 2);

The function takes two parameters: the text of a heading and a heading level. Based on the value of$headingLevel, the function builds the HTML suitable to display the heading. The example outputs the string:

<h2>User-defined Functions</h2>

The variable that is returned by areturn statement can optionally be placed in parentheses: the statementsreturn($result)andreturn $resultare identical.

Parameter Types and Return Types

The parameter and return types of a function aren’t declared when the function is defined. PHP allows parameters of any type to be passed to the function, and as with variables, the return type is determined when a result is actually returned. Consider a simple function that divides two numbers:

function divide($a, $b)
return ($a/$b);

The value returned from the function divide( ) is the value of the expression($a/$b). The type that is returned depends on the parameters passed to divide( ). For example:

$c = divide(4, 2);     // assigns an integer value = 2
$c = divide(3, 2);     // assigns a float value = 1.5
$c = divide(4.0, 2.0); // assigns a float value = 2.0

If the types of parameters passed to the function are critical, they should be tested as shown earlier in “Type Conversion.”

Thereturnstatement causes the execution of the function to end. To illustrate this, consider an improved divide( ) function definition that tests the parameter$bto avoid divide-by-zero errors:

function divide($a, $b)
   if ($b == 0)
      return false;
return ($a/$b);

If$bis 0, then the function returnsfalseand the division of$a/$bis never executed.

Thereturnstatement can also be used to exit from functions that don’t return values. Consider the following definition of bold( ) that simply prints the parameter$stringwithout any bold mark-up when passed non-string values:

function bold($string)
if (! is_string($string))
print $string;
print "<b>" . $string . "</b>";

Variable Scope

Variables used inside a function are different from those used outside a function. The variables used inside the function are limited to use within the function. This is called the scope of the variable. There are exceptions to this rule, which are discussed later in this section. Consider an example that illustrates variable scope:

function doublevalue($var)
   $temp = $var * 2;
$variable = 5;
print "\$temp is: $temp";

This example outputs the string:

$temp is:

with no value for$temp. The scope of the variable$tempis local to the function doublevalue( ) and is discarded when the function returns.

The PHP script engine doesn’t complain about an undeclared variable being used. It just assumes the variable is empty. However, this use of an undefined variable can be detected by configuring the error-reporting settings. Error reporting is discussed in Chapter 14.

The easiest way to use a value that is local to a function elsewhere in a script is to return the value from the function with thereturnstatement. The calling script can simply assign the returned value to a local variable. The following example does this:

function doublevalue($var)
$returnVar = $var * 2;
$variable = 5;
$temp = doublevalue($variable);
print "\$temp is: $temp";

The example prints:

$temp is: 10

You could have still used the variable name$tempinside the function doublevalue( ). However, the$tempinside the function is a different variable from the$tempoutside the function. The general rule is that variables used exclusively within functions are local to the function, regardless of whether an identically named variable is used elsewhere. There are three exceptions to this general rule: variables passed by reference, variables declaredglobalin the function, and superglobals that contain user and environment values and are automatically created by PHP at runtime. Global variables are discussed in the next section, and superglobals are discussed in Chapter 6.

Global variables

If you want to use the same variable everywhere in your code, including within functions, you can do so with the global statement. The global statement declares a variable within a function as being the same as the variable that is used outside of the function. Consider this example:

function doublevalue()
global $temp;
$temp = $temp * 2;
$temp = 5;
print "\$temp is: $temp";

Because$tempis declared inside the function asglobal, the variable$tempused in doublevalue( ) is a global variable that can be accessed outside the function. Because the variable$tempcan be seen outside the function, the script prints:

$temp is: 10

A word of caution: avoid overuse ofglobalas it makes for confusing code.

The global variable declaration can be a trap for experienced programmers. In some other languages, global variables are usually declared global outside the functions and then used in the functions.

In PHP, it’s the opposite: to use a global variable inside a function, declare the variable as global inside the function.


Allowing a function to modify global variables solves the problem that areturnstatement can only pass back one value. An alternative to usingglobalis to return an array of values—this approach becomes clear when we discuss arrays in Chapter 3. A better approach is to pass parameters by reference instead of by value, a practice described later.

>>> More PHP Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: