back || home || next

Tutorial 4 : functions

What is a function

You can think of a function as a machine. A machine takes the raw materials you feed it and works with them to achieve a purpose or to produce a product. A functionaccepts values from you, processes them, and then performs an action (printing tothe browser, for example) or returns a new value, possibly both.If you needed to bake a single cake, you would probably do it yourself. If youneeded to bake thousands of cakes, you would probably build or acquire a

cake-baking machine. Similarly, when deciding whether to create a function, the most important factor to consider is the extent to which it can save you from repetition. A function, then, is a self-contained block of code that can be called by your scripts. When called, the function's code is executed. You can pass values to functions, which they will then work with. When finished, a function can pass a value back to the calling code.

Define a function

You can define a function using the function statement:

function some_function( $argument1, $argument2 )

{

// function code here

}

The name of the function follows the function statement and precedes a set of parentheses. If your function is to require arguments, you must place comma-separated variable names within the parentheses. These variables will be filled by the values passed to your function. If your function requires no arguments, you must nevertheless supply the parentheses. 

Example

<?php

function myfunction()

{

print "<h1>This is my first function</h1>";

 }

 myfunction();

?>

Declaring a Function That Requires Arguments

<?php

function myfunction($name)

{

print "<h1>$name</h1><br>";

}

myfunction(“Jehan”);

myfunction(“Jane”);

myfunction(“John”);

?>

This myfunction now requires an argument as name and when we call the function elsewhere we should apply it with the required argument. 

Returning Values from User-Defined Functions

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

<?php

function addNumbers( $num1, $num2;

{

$result = $num1 + $num2 )

return $result;

}

print addNumbers(3,5);

?>

back || home || next