User Defined Functions in PHP, how to define a function in php
User Defined Functions in PHP, how to define a function in php
■User-defined functions enable developers to extract commonly used pieces of code into
separate packages, thereby reducing unnecessary code repetition and redundancies. This
separation of code into independent subsections also makes the code easier to understand
and debug.
■Because functions are defined once (but used many times), they are easy to maintain. A
change to the function code need only be implemented in a single place—the function
definition—with no changes needed anywhere else.
■Because functions force developers to think in abstract terms (define input and output
values, set global and local scope, and turn specific tasks into generic components), they
encourage better software design and help in creating extensible applications.
Syntax:
function functionname(list of arguments)
{
function code to execute;
--------
--------
{
In PHP 3.x, functions could only be invoked after they had been defined.
In PHP 4.x and PHP 5.0, functions can be invoked even if their definitions appear further
down in the program.
Using Arguments and Return Values
It is possible to create functions that accept different values from the main
program and operate on those values to return different, more pertinent results on each
invocation. These values are called arguments, and they add a whole new level of power and
flexibility to your code.
When a function is invoked with arguments, the variables in the argument list are
replaced with the actual values passed to the function and manipulated by the statements
inside the function block to obtain the desired result.
Depending on the value passed to the function, conversion is performed between two
different measurement scales.
Return value:
Usually, when a function is invoked, it generates a return value. This return value is
explicitly set within the function with the return statement.
example:
<?php
// define a function
function getTriangleArea($base, $height)
{
$area = $base * $height * 0.5;
return $area;
}
// invoke a function
echo 'The area of a triangle with base 10 and height 50 is ' . getTriangleArea(10, 50);
?>
Here, when the getTriangleArea() function is invoked with two arguments, it
performs a calculation and assigns the result to the $area variable.
This result is then returned to the main program through the return statement.
when PHP encounters a return statement within a function, it stops processing the
function and returns control to the statement that invoked the function.
If a functionis invoked with an incorrect number of arguments, PHP will generate a
warning, but still attempt to process the function. To avoid this, either make
arguments optional by setting default values for them or define your function with
support for variable-length argument lists.