Web Engineering
Web Engineering
FUNCTIONS
By
FATIMA SHOAIB
ZAINAB FATIMA
SARA
PHP Functions
Functions in PHP are blocks of code that perform specific tasks. They improve code
reusability and maintainability. PHP offers built-in functions as well as the ability to
create user-defined functions.
Basic
Syntax
function function_name (parameter1,
parameter2, ...)
{
// Code to be executed
return value; // Optional return statement
}
Components of a Function
Declaration: A function in PHP is defined using the function keyword followed
by the function name and parentheses ().
Name: Function names must start with a letter or an underscore and can be
followed by letters, numbers, or underscores. Function names are case-
insensitive in PHP.
Parameters: Functions can accept arguments (also called parameters) to work
with. Parameters are defined inside the parentheses and can have default values.
Body: The code block within {} defines the functionality of the function.
Return Value: Functions can return a value using the return keyword. If a return
is not specified, the function returns null by default .
CREATING A SIMPLE
OUTPUT
function greet($name) {
greet("Alice");
Function with Return Value
function calculateArea($length, $width) {
OUTPUT
$area = $length * $width;
return $area;
}
echo power(2);
Default Parameter Value
function power($base, $exponent = 2) OUTPUT
{
$result = pow($base, $exponent);
return $result;
}
echo power(3,3);
Recursive Function
function factorial($n)
{
OUTPUT
if ($n == 0) {
return 1; }
else {
return $n * factorial($n - 1);
}
}
FUNCTIONS fopen().
User Defined
echo greet(“Alice");
Simplified Debugging:
Errors are isolated within functions. If
something goes wrong, it’s easier to pinpoint
the issue within a specific function rather
than searching through a large script
Improved Readability:
Easier to understand and maintainImproved