Cameron Garnett/Testpage9

From WikiEducator
Jump to: navigation, search
PHP

Super Quick PHP Tutorial

Introduction | Basic Syntax | Sending Data to the Browser | Comments | Variables | Strings | Functions | Quotes | Debugging | Form


VmvIcon Objectives.png

Learning Objectives

By the end of this page you will know what a function is and how to write them using php code.

Functions

  • A function is a block of statements that can be used repeatedly in a program.
  • A function name can start with a letter or underscore (not a number).
  • Give the function a name that reflects what the function does!


VmvIcon Example.png

Example

This is a basic skeleton of a function.

function functionName() {
code to be executed;
}

PHP has more than 1000 built-in functions. If you don't think that is enough then you can create your own.

User Defined Functions
To create a user defined function in PHP you need to start with the word function.
In this first example I will create a function called displaystring(). The first curly bracket indicates the start of the code and the second curly bracket indicates the end of the function. Very similar to javascript.


VmvIcon Example.png

Example

<?php
function displaystring() {
echo "Today I went to the Zoo!";
}

displaystring(); // calls the function. The output will be Today I went to the Zoo!
?>


In the next example to get a function to return a sum use the return statement. The $x and the $y inside the brackets are parameters.

VmvIcon Example.png

Example

<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "4 + 6 = " . sum(4,6) . ";
echo "8 + 12 = " . sum(8,12) . ";
echo "3 + 4 = " . sum(3,4) . ";
?>


VmvIcon Objective.png

Activity

Write the previous code into notepad++ and experiment with the format of functions.