News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

PHP Tutorial – 09 – Functions

A function is a reusable code block that will only execute when called.

Defining functions

To create a function the function keyword is used followed by a name, a set of parentheses and a code block. The naming convention for functions is the same as for variables – to use a descriptive name with each word initially capitalized, except for the first one.

function myFunc() 
{ 
  echo "Hello World"; 
}

A function code block can contain any valid PHP code, including other function definitions.

Calling functions

Once defined a function can be called (invoked) from anywhere on the page, by typing its name followed by a set of parenthesis. Function names are case-insensitive, but it is good practice to use the same casing as they have in their definition.

myFunc(); // "Hello World"

A function can be called even if the function definition appears further down in the script file.

foo(); // ok
function foo() {}

An exception to this is where the function is only defined when a certain condition is met. That conditional code must then be executed prior to calling the function.

bar(); // error 
if (true) { function bar() {} }
bar(); // ok

Function parameters

The parentheses that follow the function name are used to pass arguments to the function. To do this the corresponding parameters must first be specified in the function definition in the form of a comma separated list of variables. The parameters can then be used in the function.

function myFunc($x,$y) 
{ 
  echo $x . $y; 
}

With the parameters specified the function can be called with the same number of arguments.

myFunc('Hello', ' World'); // "Hello World"

To be precise, parameters appear in function definitions, while arguments appear in function calls. However, the two terms are sometimes used interchangeably.

Default parameters

It is possible to specify default values for parameters by assigning them a value inside the parameter list. Then, if that argument is unspecified when the function is called the default value will be used instead. For this to work as expected it is important that the parameters with default values are declared to the right of those without default values.

function myFunc($x, $y = " Earth") 
{ 
  echo $x . $y; 
} 
 
myFunc("Hello"); // "Hello Earth"

Variable parameter list

A function cannot be called with fewer arguments than is specified in its declaration, but it may be called with more arguments. This allows for the passing of a variable number of arguments, which can then be accessed using a couple of built-in functions. For getting one argument at a time there is the func_get_arg function. This function takes a single argument, which is the parameter to be returned starting with zero.

function myFunc() 
{ 
  $x = func_get_arg(0); // get specified argument
  $y = func_get_arg(1);	
  $z = func_get_arg(2);	 
  echo $x . $y . $z;
}  
 
myFunc('Fee', 'Fi', 'Fo'); // "FeeFiFo"

There are two more functions related to the argument list. The func_num_args function gets the number of arguments passed and func_get_args returns an array containing all of the arguments.

function myFunc() 
{ 
  $num  = func_num_args();
  $args = func_get_args();
  for ($i = 0; $i < $num; $i++)
    echo $args[$i] . ' ';
}
 
myFunc('Fee', 'Fi', 'Fo'); // "Fee Fi Fo"

Return statement

Return is a jump statement that causes the function to end its execution and return to the location where it was called.

function myFunc() 
{ 
  return; // exit function
}

It can optionally be given a value to return, in which case it will make the function call evaluate to that value.

function myFunc() 
{ 
  return 'Hello'; // exit function and return value
}   
 
echo myFunc(); // "Hello"

A function without a return value will be evaluated as null.

Scope and lifetime

Normally, a PHP variable’s scope starts where it is declared and lasts until the end of the page. However, a local function scope is introduced within functions. Any variable used inside a function is by default limited to this local scope. Once the scope of the function ends, the local variable is destroyed.

$x = 'Hello'; // global variable
 
function myFunc() 
{ 
  $y = ' World'; // local variable
}

In PHP, trying to access a global variable from a function will not work and will instead create a new local variable. In order to make a global variable accessible the scope of that variable must be extended to the function by declaring it with the global keyword.

$x = 'Hello'; // global $x
 
function myFunc() 
{ 
  global $x;      // use global $x in this function
  $x .= ' World'; // change global $x
}
 
myFunc();
echo $x; // "Hello World"

An alternative way to access variables from the global scope is by using the predefined $GLOBALS array. Note that the variable is specified as a string without the dollar sign.

function myFunc() 
{ 
  $GLOBALS['x'] .= ' World'; // change global $x
}

In contrast to many other languages, control structures – such as loop and conditional statements – do not have their own variable scope. A variable defined in such a code block will therefore not be destroyed when the code block ends.

if(true)
{
  $x = 10; // global $x
}
 
echo $x; // "10"

In addition to global and local variables PHP has property variables, which will be looked at in the next chapter.

Anonymous functions

PHP 5.3 introduced anonymous functions, which allow functions to be passed as arguments and assigned to variables. An anonymous function is defined like a regular function, except that it has no specified name. The function can be assigned to a variable using the normal assignment syntax, including the semicolon.

$say = function($name)
{
  echo "Hello " . $name;
};
 
$say("World"); // "Hello World"

An anonymous function can inherit variables from the scope where it is defined. Such inherited variables are specified with a use clause in the function header.

$x = 1;
$y = 2;
 
$callback = function($z) use ($x, $y) 
{
  return $x + $y + $z;
};
 
echo $callback(3); // "6"

Function overloading

Unlike many other languages, PHP does not allow a function to be defined multiple times with different parameters. This feature, called function overloading, has the benefit of allowing a function to handle a variety of parameters transparently to the user.

Although PHP does not have function overloading, it is possible to achieve a similar behavior. Since PHP does not have strong typing, a function parameter already accepts any data type. This loose typing – along with default parameter values and variable parameter lists – makes it possible to duplicate the effect of function overloading.

// Prints a variable number of parameters
function myprint() 
{
  $a = func_get_args();
  foreach ($a as $v) { echo $v; }
}
 
myprint(1,2,3); // "123"

Built-in functions

PHP comes with a large number of built-in functions that are always available, such as string and array handling functions. Other functions depend on what extensions PHP is compiled with, for example the MySQL extension for communicating with MySQL databases. For a complete reference of the built-in PHP functions see the PHP Function Reference.

Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours