Creating reusable code(functions) September 24, 2008
Posted by me2blog in Basic PHP programming, php.Tags: Defining functions, functions in PHP, global variables, php, return values in functions
trackback
A function is a group of PHP statements that perform a specific task, u can use the function whenever u need to perform the task.
Defining functions:
function function_name ()
{
block of statements
return;
}
The return statement stops the function and returns to the main script, it is not required but it makes the functions easier to understand.U can write a function anywhere in the script, but the usual is to put all functions together at the beginning of the script file.
Returning values back from functions:
U can pass value back from a function, using the return statement. it can only return one value. However remember that the return value can be an array; thus it is actually more than one value!
u can also use the return statement in a conditional statement to end the function.
Example:
<?php
function welcome()
{
echo “Welcome”;
return;
}
function name()
{
return Noor;
}
?>
<h3> Functions in PHP </h3>
<?php
$name_variable= name();
welcome();
echo “ $name_variable”;
?>
The output:
Functions in PHP
Welcome Noor
Using variables in functions (another method to return more than 1 value):
u can create as many variables as u wish inside the function, these variables r local. which means that they r accessable inside the function, also notice that the function can’t access any variable inside the function except in the case that this variable is set to be global!
by using global variables inside the function, u can return as many value as u wish
Example1 ( Local variables ,,, notice how u don’t get the result u want ):
<?php
$x=3;
$y=2;
function addition()
{
$sum= $x + $y;
}
addition();
echo “The sum result =”, $sum;
?>
The output for the first example:
The sum result =
Example2:
<?php
function addition($x1,$y1)
{
global $sum;
$sum= $x1 + $y1;
return;
}
$x=5;
$y= 2;
addition($x,$y);
echo “The sum result =”, $sum;
?>
The output for Example2:
The sum result =7

Comments»
No comments yet — be the first.