IPT home IPT A Virtual Approach by Peter Whitehouse
Quick Links:
Information and Intelligent Systems Social and Ethical Implications Human Computer Interaction Software and Systems Engineering eXercise Files Course Outline and Assessment A-Z of Geeky Acronyms Terrace Work Program 2004 Sillybus FAQ = Frequently Asked Questions Help

PHP Functions

Defining Sub-Programs for Modularity

Variables & Operators | Input & Output | Decisions & Loops| Sub-Programming | Built-ins

Functions as containers for code

These are simple, wrap your code in a function name and you can call it whenever you need it


function sayHi(){
echo 'hi there<br />'; }

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.


function greet($thing){
printf('Hello %1s and I really mean that',$thing); }
person = 'Fred';

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


function cube($num){
    $answer = $num*$num*$num;
return $answer }
echo 'The cube of 9 is '.cube(9);



©Copyright t 1992..2017+. Edition 25.150117
Creative Commons License
This work is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 2.1 Australia License