ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations

Introduction to Functions: Part 2

08/09/2001

Today we'll revisit our discussion of functions and introduce several new topics, including scope, static variables, and return values.

The last time we spoke about functions, we took a fairly basic look at how they work and how they can be used in your scripts. This included declaring functions both with and without parameters, as well as how to declare default values for any parameters that the function may require. Today we'll extend on that discussion and explain many advanced topics dealing with functions. To begin, we'll start with the concept of function scope and how it can affect you when developing your own functions.

Variable Scope

For those of you with programming experience, the term "scope" may already be familiar to you. For those who are not familiar with the term "scope," it refers to the concept that a variable inside of a function cannot be inherently accessed by parts of the script which reside outside of that function. To better illustrate this, let's take a look at a bit of color-coded code and an associated diagram:

<?php
  function myfunction() {
   echo $foo;
  }

  $foo = "Hello";
  myfunction();
  echo $foo;
?>

When this code is executed, what will the output be? A reasonable answer to this question would be to say that we would echo the value of $foo twice, and hence the string "Hello" would be outputted twice to the browser -- but this is not the case. Although the variable $foo will be outputted twice to the browser, the result will only be a single "Hello." The reason this occurs is because the variable $foo inside of myfunction() is a completely different variable from the one outside of the function. That is to say, the "scope" of $foo within myfunction() is local to that function and separate from any other variables named $foo that reside outside of that function. This separation of same-name variables inside and outside a function is an important characteristic trait of PHP scripts. In order to access the variable $foo from within myfunction(), we'll need to introduce a new statement: global.

The Global Statement

The global statement's purpose is to allow a developer to access a variable outside the scope of a given function. The syntax for global is as follows:

global $var1, $var2, $var3, .... ;

Where $var1, $var2, etc. represent the different variables you which to access from within your function. To demonstrate how global works, we'll return to our example above and use the global statement to fix our bug and make the script output the contents of $foo twice:

<?php
  function myfunction() {
   global $foo;
   echo $foo;
  }

  $foo = "Hello";
  myfunction();
  echo $foo;
?>

Because of the use of the global statement in myfunction(), we have instructed PHP to treat all references to the variable $foo inside of the function the same as it would as if it was not a part of the function at all and within the same scope as the rest of the script. The result is the variable $foo will be outputted to the browser twice, once in the normal part of the script and then again in the function that the script calls.

Persistent Function Variables

Related Reading

PHP Pocket ReferencePHP Pocket Reference
By Rasmus Lerdorf
Table of Contents
Sample Section
Full Description
Read Online -- Safari

Another interesting behavior when dealing with functions in PHP is the concept of persistent variables. Under normal circumstances, the life of a variable within a PHP function starts when the variable is first initialized within the function (either as a parameter or a declared variable) and ends when the function has been executed and the script continues. Under some circumstances, it would be beneficial if PHP could remember certain variables stored within a function to be used next time the function is called. For example, what if we wanted to make a function that remembered how many times it had been called throughout the script? We'll show you how you can use static variables to accomplish this task.

The Static Keyword

The static keyword is used when declaring a variable in PHP. It's purpose is to inform PHP that this variable should not be destroyed when the a given function executes, but rather its value should be saved for the next time it is needed. The syntax is:

static [var] $variable [= <initial value>]

In a script without functions the static keyword serves no purpose, since regardless of what type of variable it is, PHP will destroy it when the script is finished executing. However, when dealing with functions it can be used to retain certain desired variables within that function for the life of the script's execution. To illustrate this we'll now use the static keyword to count how many times a given function has been called:

<?php
  function staticfunction() {
   static var $count = 0;
   $count++;
   echo "Function has executed $count time(s)";
  }

  for($i = 0; $i > 5; $i++) {
   staticfunction();
  }
?>

Under normal circumstances, this function would execute five times and each time the output would be:

Function executed 1 time(s)

Because each time the function is called the variable $count would be created with the value of 0 and destroyed at the end of the function. Instead, because we did use the keyword static to define our variable, it is initialized a single time to the value of 0 and saved at the end of the function to be used next time the function is called. The result of calling the function five times under this circumstance will be:

Function executed 1 time(s)
Function executed 2 time(s)
Function executed 3 time(s)
Function executed 4 time(s)
Function executed 5 time(s)

Returning Values From Functions

As you may or may not have noticed, variables are often assigned values based on the execution of a function. For example, here we are using the built-in function count() to assign the variable $items the number of elements in array $foo:

<?php 
  $items = count($foo);
?>

Until now, all of the functions we have discussed are unable to function in this manner. This procedure is called "returning" from a function and, appropriately enough, we can do so with the use of the return statement.

The Return Statement

return statements are used when you would like to be able to assign a variable's value based on the results of the execution of a particular function, as we did with the count() function above. Use of the return statement is very straightforward, so we'll jump right into the formal definition and a small piece of example code:

return <value>;

Where value represents any value available in PHP, including an array. For example, the following is used to assign the variable $foo with "Yes" or "No," depending on the parameters passed the to function:

<?php
  function greaterthan($val1, $val2) {
   if($val1 > $val2) {
    return "Yes";
   } else {
    return "No";
   }
  ?>

  $foo = greaterthan(5, 2);
  echo "Is 5 greater than 2? -- $foo!";
?>

The result of the above script will be:

Is 5 greater than 2? -- Yes!

Final Notes

And so concludes our introduction to functions. With what we have learned in this series, we should now be able to work with functions in confidence and use them when appropriate in our scripts. However, the discussion is far from over! Come back soon for a continuation of this series to learn about advanced function topics and how they can be used to improve the way your scripts function. Happy coding!

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.