Functions in PHP

From Wiki

Jump to: navigation, search


The basic syntax for using (or calling) a function is:

function_name(expression_1, expression_2, ..., expression_n)

This includes the name of the function followed by a parenthesized and comma-separated list of input expressions. Functions can be called with zero or more arguments, depending on their definitions. When PHP encounters a function call, it first evaluates each argument expression and then uses these values as inputs to the function. After the function executes, the returned value (if any) is the result of the entire function expression.

All the following are valid calls to built-in PHP functions:

sqrt(9) // square root function, evaluates to 3
rand(10, 10 + 10) // random number between 10 and 20
strlen("This has 22 characters") // returns the number 22
pi() // returns the approximate value of pi

Every function call is a PHP expression, and (just as with other expressions) there are only two reasons why you might want to include one in your code: for the return value or for the side effects.

The return value of a function is the value of the function expression itself. You can do exactly the same things with this value as with the results of evaluating any other expression. The result of a function may be of any type, and it is common to use the array type as a way for functions to return multiple values.

Functions are also used for a wide variety of side effects, including writing to files, manipulating databases, and printing things to the browser window. It's fine to make use of both return values and side effects at the same time-for example, it is very common to have a side-effecting function return a value that indicates whether or not the function succeeded.

Variable Scope in Functions

The basic principle governing variables in function bodies is:

Excepting some special declarations, the meaning of a variable name inside a function has nothing to do with the meaning of that name elsewhere.

There is a small set of global variables that are automatically visible from within function definitions. These are the superglobal arrays ($_POST, $_GET, $_SESSION, and so on), which contain keys and values corresponding to variable bindings from different sources.

A function has access only to the formal parameter variables (which have the values copied from the actual parameters), plus any variables assigned inside the function. This means that you can use local variables inside a function without worrying about their effects on the outside world.

The default scope of a variable defined inside a function is local. Using the global declaration, you can inform PHP that you want a variable name to mean the same thing as it does in the context outside the function. The syntax of this declaration is simply the word global, followed by a comma-delimited list of the variables that should be treated that way, with a terminating semicolon.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Global versus local variables</title>
 <?php
  function sayMyABCs2 (){
   global $count;
   while ($count < 10){
    print(chr(ord('A') + $count));
    $count = $count + 1;
   }
   print("<p>Now I know $count letters</p>");
  }
 ?>
</head>
<body>
<?php
 $count = 0;
 sayMyABCs2();
 $count = $count + 1;
 print("<p>Now I've made $count function call(s).</p>");
 sayMyABCs2();
 $count = $count + 1;
 print("<p>Now I've made $count function call(s).</p>");
?>
</body>
</html>

and the result is:

ABCDEFGHIJ
Now I know 10 letters
Now I've made 11 function call(s).
Now I know 11 letters
Now I've made 12 function call(s).

By default, functions retain no memory of their own execution, and with each function call local variables act as though they have been newly created. The static declaration overrides this behavior for particular variables, causing them to retain their values in between calls to the same function.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Static variables</title>
  <?php
   function sayMyABCs3 (){
    static $count = 0; //assignment only if first time called
    $limit = $count + 10;
    while ($count < $limit){
     print(chr(ord('A') + $count));
     $count = $count + 1;
    }
    print("<p>Now I know $count letters</p>");
   }
 ?>
</head>
<body>
<?php
 $count = 0;
 sayMyABCs3();
 $count = $count + 1;
 print("<p>Now I've made $count function call(s).</p>");
 sayMyABCs3();
 $count = $count + 1;
 print("<p>Now I've made $count function call(s).</p>");
?>
</body>
</html>

This version gives the following output:

ABCDEFGHIJ
Now I know 10 letters
Now I've made 1 function call(s).
KLMNOPQRST
Now I know 20 letters
Now I've made 2 function call(s).


Function Scope

Although the rules about the scope of variable names are fairly simple, the scoping rules for function names are even simpler.

There is just one rule in PHP5: Functions must be defined once (and only once) somewhere in the script that uses them.

It is very common to want to use the same set of functions across a set of Web site pages, and the usual way to handle this is with either include or require, both of which import the contents of some other file into the file being executed. Using either one of these forms, when you want to modify your functions, you will have to do it only once.

For example, at the top of a PHP code file we might have lines like:

include "basic-functions.inc";
include "advanced-functions.inc";
// code that uses basic and advanced functions 

Both include and require have the effect of splicing in the contents of their file into the PHP code at the point that they are called. The only difference between them is how they fail if the file cannot be found.

  • he include construct will cause a warning to be printed, but processing of the script will continue;
  • require, on the other hand, will cause a fatal error if the file cannot be found.

When you include a filename, PHP searches for a file by that name in the directories specified in the include_path (which is settable in your php.ini file). The default path includes the same directory as the one the top-level code page is in.

See also: User-defined Functions
Personal tools