|
|
|
PHP Functions

Programmer-defined functions
- Despite PHP’s many built-in functions, there will be many times you will want to create your own functions.
- Reasons for creating functions:
- reusable code
- easier to manage and debug code which has been broken down into smaller parts
- Functions:
- are defined using the function keyword
- names should be meaningful, but must begin with a letter or underscore, and then may contain letters, numbers, or underscores
- names are case insensitive
- may take arguments, which are limited in scope – you can use any variable name, but by practice, name them differently than any global variables
- when a function ends, it can give a “reply” to the code that called it by returning a value – use the return keyword
The syntax for creating your own functions is:
function function_name( ) {
statements;
} |
To call the function use the function name.
Arguments
- PHP functions can take arguments or parameters.
- You can create functions to take as many arguments as necessary, but they must be passed in the proper order.
- Failure to send the correct number of variables will result in an error.
- use return statement to return a value
1 |
<? |
2 |
function multiplyThem( $n1, $n2 ){ |
3 |
$product = $n1 * $n2; |
4 |
return $product; |
5 |
} |
6 |
$x = 3; |
7 |
$y = 4; |
8 |
$z = multiplyThem( $x, $y ); |
9 |
echo "$z"; |
10 |
?> |

Default Arguments
- setting a default value for an argument makes it optional
- passed values overwrite the default
- place default arguments last in function definition
1 |
<? |
2 |
$x = 3; |
3 |
echo(multiplyThem( $x )); |
4 |
function multiplyThem( $n1, $n2 = 10 ){ |
5 |
$product = $n1 * $n2; |
6 |
return $product; |
7 |
} |
8 |
?> |
- You can set as many default values as you need, as long as you place them last in the function definition. Required arguments must come first.
Variable scope
- The scope of a variable used in a function is local to the function by default
- To create a global variable use global keyword
1 |
<? |
2 |
function multiplyThem( $n1, $n2 = 10 ) { |
3 |
global $product; |
4 |
$product = $n1 * $n2; |
5 |
return $product; |
6 |
} |
7 |
multiplyThem(5); |
8 |
echo $product; |
9 |
?> |

|
|