PHP Procedures
Procedures are a type of subroutine that you can create in a PHP script to use on your Web page. By definition, a procedure is a block of code that performs a task without returning a value the way a function does. However, PHP does not make a strong distinction between procedures and functions in the way you define them.
-
Purpose
-
A procedure lets you repeatedly use the same block of code in your PHP script instead of writing the same code multiple times. Procedures perform calculations or modify values passed to them or created within them to display on the Web page. For example, a subroutine that takes two integers as arguments, multiplies them together and uses the "echo" function to show the result is an example of a procedure. In essence, procedures are small programs contained within the larger program.
Definition
-
To create any kind of subroutine in PHP, including a procedure, you use the "function" keyword followed by the procedure's name, argument list and declaration. For example, typing "function myfunc($var) { <body> }" create a procedure called "myfunc" that accepts one argument. Do not code a return value. In PHP, you cannot create multiple procedures with the same name, nor can you overload a function like you can in some other programming languages.
-
Arguments
-
You can create procedures that accept any number of parameters, and then modify them as needed within the body of the procedure's code. You do so by creating PHP variables or by passing by reference, where you include a & sign before the variable. When you call a procedure elsewhere in your script, you must pass the same number of arguments to it that are called for in the procedure's definition. You can pass variables or string literals in the procedure call.
Scope
-
You can declare one procedure nested within another procedure, but you cannot use the nested procedure unless you first call the parent procedure, so the Web page can process the code. Likewise, if you create and initialize a variable, and then pass it to a procedure and modify its value, the original variable's value remains unchanged. You can also create multiple variables all with the same name in separate procedures. None of them are related to each other.
-