Section 0: Module Objectives or Competencies
Course Objective or Competency |
---|
The student will be able to write basic PHP applications in order to connect to and manipulate a database using PHP. |
Section 1: Overview
A discussion of functions must include both user-defined functions and built-in functions.
Similarly, user-defined functions require an explanation of how to declare the function, how to pass arguments, how to return values, how to call the function, etc.
Section 2: User-Defined Functions: Function Declaration
A function may be defined using syntax like the following:
function greet()
{
echo date('l, F dS Y.');
}
In general, functions need not be defined before they are referenced.
All functions and classes in PHP have the global scope.
Here are more details and a simple example (text version).
Section 3: User-Defined Functions: Function Arguments
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.
PHP supports passing arguments by value (the default – gets a copy), passing by reference (actually references the value), and default argument values.
- Variable-length argument lists are also supported.
// Example of a value argument
function displayError ($error)
{
echo '<p class="error">' . $error .
'</p>';
}
Reference Arguments
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function).
To allow a function to modify its arguments, they must be passed by reference.
- To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.
function addGoodStuff(&$string)
{
$string = 'My favorite classes are ' .
$string . ' and INFO 4430!';
}
Here is a sample call:
$favoriteClass = 'INFO 4407';
addGoodStuff($favoriteClass);
echo $favoriteClass;
Here is a demo (with text version) and more details.
Section 4: User-Defined Functions: Returning Values
To code a function that returns a value, include a return statement.
function square ($num)
{
return $num * $num;
}
Here is a sample call:
$num = 4;
echo $num . ' squared is ' . square($num);
Here is another sample call, in which the return value is assigned to a variable:
$num = 8;
$result = square($num);
echo $num . ' squared is ' . $result;
Click for some additional examples. Oh, and the demo (with text file).
Section 5: User-Defined Functions: Function Call
From previous examples the function call should be obvious.
Function calls can be embedded in statements or appear as standalone statements.
displayError ("Something is terribly wrong!");
$result = square($num);
Section 6: Built-in Functions
PHP provides a wide variety of built-in functions.
For a complete reference and examples of the built-in functions, please visit the W3Schools PHP 7 Reference.
The PHP Manual provides additional details.