Home / code / php

Functions in PHP

In PHP 3, if you make your own functions they must be defined before they are referenced. No such requirement exists in PHP 4.

function foo ($arg_1, $arg_2)
{
    echo "Example function.\n";
    return $retval;
}

PHP does not support function overloading, nor is it possible to undefined or redefine previously-declared functions.

Function Arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of variables and/or constants.

function takes_array($input)
{
  echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}

Making arguments be passed by reference

By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference.

function add_some_extra(&$string)
{
  $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'

Default arguments

A function may define C++-style default values for scalar arguments as follows:

function makecoffee ($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee ();
echo makecoffee ("espresso");

 

TOP

Latest script:

 

Books: