[main] [misc] [graphics] [page design] [site design] [xhtml] [css] [xml] [xsl] [schema] [javascript] [php] [mysql]

HVCC Home
Blackboard HVCC
Blackboard Manual
Faculty Association

php main
1. what is php
2. http basics
3. php basics
4. php expressions
5. php client side
6. php flow control
a. php conditionals
b. php adv conditions
c. php iteration
* d. php functions
e. php adv functions
f. php modularity
7. php manual


print version

Note that all external links will open up in a separate window.

This is a stripped down version of these pages for older browsers. These pages are really meant to be viewed in a standards compliant browser.

Directions for surfing with audio.

Functions

These tutorials are about PHP and its use for server-side Web programming.

Functions

function: a named segment of code that can be invoked to perform some task, or function

A function is a statement block that has been assigned a name.

That name allows it to be called or referred to, meaning the it can be invoked by name to perform some task, or function. This means that you can create a piece of code that will not run until specifically called for or invoked by another piece of code.

Being able to defer the execution of code until it is called for is a very powerful tool. It allows us to step out of linear, batch processing mode and instead operate in an event driven environment.

Defining Functions

In PHP a function is defined as follows:

function functionName(parameter) {
  statements;
  return;
  }
  • The definition starts with the keyword function.
  • This is followed by the name of the function.
  • After that comes a set of parentheses containing the parameters, or input values, the function is expecting to receive. Each parameter must be a variable name. These variables are created by declaring them as parameters and are local to the function. Sometimes you will hear parameters called arguments. Technically an argument is what is sent and a parameter is what the function is expecting to receive. Most textbooks authors pick one or the other term and just stick with it, so you can cinsider them to be interchangeable words.
  • After this comes the curly braces that delimit the statement block that makes up the body of the function.
  • The last statement in the statement block should be a return statement, which returns control back to whatever called the function. The keyword return can stand alone or it can be followed (with no intervening line break) by a value to be returned. If no value is specified, then the function returns null.
function testVal($x) {
  if (!(is_int($x))) {
    echo "$x is not a number!";
    }
  return;
  }

function strangeEquation(x, y, q) {
  var z = x * y;
  var p = q - 7;
  return (z * x % (y + 1)) / p;
  }

When trying to figure out what to name your functions, you only need to remember a few basic rules.

  • PHP function names are not case sensitive. Therefore, fname(), Fname(), and FNAME() all refer to the same function.
  • The function name can only contain letters from the ASCII character set, digits, and the underscore.
  • The function name cannot begin with a digit.
  • You cannot give a function the same name as another function or reserved keyword. PHP does not support function overloading.

Invoking Functions

You invoke, or call, a function by name. The name needs to be followed by a set of parentheses that contain zero or more values to be passed to the function, called the arguments for the function call. The number of values being passed should be equal to the number of parameters the function has. The values are assigned to the parameters in the order in which they appear defined in the function's parameter list.

Invoking a function:

$x = 'bob';
testVal($x);

$x = 1;
$y = 2;
$q = 3;
strangeEquation($x, $y, $q);

If you want to pass values of a certain type, you need to test for this yourself since PHP, being a loosely typed language, does not check.

If you pass too many arguments, then the additional values do not get assigned to named paraeters. They can still be accessed within the function, just not as named variables from the parameter list.

If you pass too few arguments, then the remaining parameters will be set to null. PHP will generate an error message about this, but will try to run the function anyway.

If you don't want to pass certain arguments, you cannot use the empty comma notation as you can in some languages. Instead you just need to put null values in those locations.

 Wrong:
$x = fName(,,$c);

 Right:
$x = fName(null,null,$c);

Passing by Reference

PHP always passes by value, including objects and arrays. Anyone shocked by this has had plenty of experience with object oriented programming. But for the rest of us:

There are two primary models for passing data back and forth in a program. One is pass by value and the other is pass by reference. Pass by value means that when you pass the variable by sending it as an argument to a function, or assigning it to another variable using an assignment operator, a copy of the value of the variable is made and that is what is passed to the receiving function or variable.

It works like this: If I set $a equal to 7, and then say $b = $a, I will then have two variables each storing the value if 7. If I change either one, it won't affect the other one. It is like a photocopy. After I have made the copies, writing something on one copy won't affect the other copies.

Pass by reference is a little more complicated and normally only occurs in object oriented environments. To understand it, it first helps to understand that variables are actually just pointers pointing to values stored in memory. Pass by value works by creating a new pointer pointing to a new location in memory with a copy of the stuff from the old location copied over to the new location. Pass by reference created a new pointer but points it to the exact same location. It is not actually passing the value anywhere, it is just creating new variables pointing to the exact same thing. Another way of saying it is that it creates an alias for the current variable instead of making a copy.

So what happens if you want to pass by reference instead of pass by value? The way you do this is with the ampersand (&). You use the ampersand with function parameters and with the assignment operator to say that you want the variable passed by reference instead of value.

Thus to create an alias by simple assignment with passing by reference, you would write:

$a =& $b;

Notice that the ampersand comes after the assignment operator. It is functioning as an operator to get a reference to the variable after it. In terms of order of precedence, the code is executed like this:

$a = (& $b);

To pass by reference into a function, the ampersand needs to appear in the parameter expecting to receive the value, not in the call to the function. Since there is no assignment operator involved, the parameters are just prefixed with the ampersand.

 Right:
$x = fName(&$a, &$b);

 Wrong:
fName(&$a, &$b);

An alternate method is provided below, but only works if the function is always called with the same variables.

You can use a pass by reference call to recieve a value back from a function, but it is only useful if the function is returning a global variables. Even with a pass by reference, local variables will not be available outside the function because they will go away when the function has terminated.

Global and Static Variables

PHP is slightly odd in that variables defined outside of functions, which we would normally consider to be global are not accessible from within functions. They are, in essence, local to the global environment. So how do we get at those values within a function without passing all of them in as arguments.

PHP provides two methods for getting global variables into functions.

The first is the $GLOBALS[] array, which is a super-global array that stores all user defined global variables. Thus, you can access a global variable called $thisVar within the function with $GLOBALS["thisVar"].

The second method is to use the global keyword. It is used inside the function to create references to global variables into the function. Prefixing a variable, or list of variables, with the word global as its own complete statement declares that you want to use the variable within the function. Note that this is not passing a copy or a reference in to the function, it is making the variable available within the function. Changes to the varaible will show up outside the function.

function abc() {
  global $x;
  global $a, $b, $c;
  [...]
}

Static variables are variables that are local to the function but persist across instances of the functions execution. Normally local variables within functions are created when the function is called and destroyed when the function is finished. If you want local variables to persist across calls to the function, you can use the static keyword when declaring the variable. This will cause the variable to only be initialized during the first call to the function. During subsequent calls, the function will check to see if the variable already exists. If it does, it will work with the value that already exists.

function abc() {
  static $x;
  static $a = 7;
  [...]
}

[top]