PHP Functions
Defining Sub-Programs for Modularity
Functions as containers for code
These are simple, wrap your code in a function name and you can call it whenever you need it
eg:
<?php
function sayHi(){ echo 'hi there<br />';
}
sayHi()
?>
The parameter brackets are necessarily left blank (no parameters, right?) and the call is naturally the name of the function with an empty parameter list
Functions with parameters
PHP is loosely typed, so you can introduce parameters without casting them a data type, by association, the call will cast them - this can cause issues if your functions do type-specific things with the incoming values but if you know what is what, all is cool.
eg:
<?php
function greet($thing){ printf('Hello %1s and I really mean that',$thing);
}
person = 'Fred'; greet(person);
?>
The named parameter appears as an accessible local variable inside the function. There can be lots of listed paramaters, so long as you use them in the order you mean to in teh call, all is sweet.
Functions with Returns
The only addition here is the word RETURN in front of what oyu want your function to come back with - this creats an issue in that the finction will generate a value that will need to be stored somewhere (typically a variable) or used directly in a builtin call
eg:
<?php
function cube($num){
$answer = $num*$num*$num; return $answer
}
echo 'The cube of 9 is '.cube(9);
?>
|