PHP Lessons

Functions 1

A PHP function includes both the procedures and the pure functions that return an y value depending on an x value.

A function - procedure is fundamentally an enlargement of the PHP vocabulary.

If you want to use a set of instructions more times (in different files, too), you can substitute the group of instructions by a word only, i.e. by a call of function.

Functions must be declared before their call, so that PHP can learn their meaning.

The declaration of a function is genarally made at the beginning, in the head section of the file (it must be a PHP file), but it can be made in a separate file.

Look at the syntax of the function declaration:

function declaration: PHP codenotes
<?php

function name (parameter)
{
instruction;
instruction;
...;
};

?>
The keyword is function
followed by the name of the function.
The parameter (or the parameters) are optional.
The function is described by PHP instructions
between curly bracket.
The declaration ends by a semicolon.
function enter ($x) {
echo"type the value of $x:
<input type='text' name=$x>
<input type='submit'>";
};
The enter ($x) function substitutes the instructions
to enter a value by an input format.
A generic $x parameter is used.
function menu() {
echo"
<a href='#'>page 1</a>
<a href='#'>page 2</a>
<a href='#'>page 3</a>
};
The menu() function substitutes the instructions
to make a list of links.
In this case it doesn't use parameters.
The function call is made inside the program (in the body), every time you need it.
PHP codeoutput
enter (a); type the value of a:
enter (b); type the value of b:
menu(); page 1 page 2 page 3

If you want to use the function in more files, as for the menu() function, it's a good idea to declare it in a separated file, instead of writing it every time.

For example, you can write the declaration of the menu() function, as well as other useful functions, in a file utility.php.

Every file which uses those functions must have the following instruction in the head:
require "./utility.php";

Valid HTML 4.01 Transitional