Functions

A function is a named sequence of code statements that can optionally accept parameters and return a value. A function call is an expression that has a value; its value is the returned value from the function. PHP provides a large number of internal functions. The “Function Reference” section lists all of the commonly available functions. PHP also supports user-definable functions. To define a function, use the function keyword. For example:

function soundcheck($a, $b, $c) {
 return "Testing, $a, $b, $c";
}

When you define a function, you need to be careful what name you give it. In particular, you need to make sure that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts with an internal function, you get the following error:

Fatal error: Can't redeclare already declared function in filename on line N

After you define a function, you call it by passing in the appropriate arguments. For example:

echo soundcheck(4, 5, 6);

You can also create functions with optional parameters. To do so, you set a default value for each optional parameter in the definition, using C++ style. For example, here’s how to make all the parameters to the soundcheck( ) function optional:

function soundcheck($a=1, $b=2, $c=3) {
 return "Testing, $a, $b, $c";
}

Variable Scope

The scope of a variable refers to where in a program the variable is available. If a variable is defined in the main part of a PHP script (i.e., not inside a function ...

Get PHP Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.