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

Home | 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

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);
?> 

 

 

wonko@wonko.info
©Copyright t 1992..2018+. Edition 26.150117
wonkosite
Creative Commons License
This work is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 2.1 Australia License
.