6. Basic Functions in PHP
6. Basic Functions in PHP
Functions are blocks of reusable code that perform specific tasks. They help reduce redundancy,
enhance readability, and improve the structure of PHP programs.
Definition
Syntax
function functionName() {
// Code to execute
}
Example
function greet() {
echo "Hello, welcome to PHP!";
}
Real-World Application
Function Parameters
Syntax
function functionName($parameter1, $parameter2) {
// Code to execute
}
Return Values
• A function can return data to the caller using the return keyword.
Real-World Application
3. Variable Scope
Definition
A. Local Variables
• Defined inside a function and can only be accessed within that function.
• They are temporary and exist only during the function's execution.
Example
function showLocal() {
$localVar = "I am local";
echo $localVar;
}
B. Global Variables
function showGlobal() {
global $globalVar;
echo $globalVar;
}
C. Static Variables
Example
function countCalls() {
static $count = 0; // Retains value across calls
$count++;
echo "Function called $count times<br>";
}
• Parameters act as local variables and are initialized with values passed during function
calls.
Example
function greetUser($name) {
echo "Hello, $name!";
}
1. Greeting System
function greet($timeOfDay) {
return "Good $timeOfDay!";
}
BASIC PHP - FUNCTIONS SOMATECH IT
echo greet("Morning"); // Outputs: Good Morning!
2. Discount Calculator
function calculateDiscount($price, $discountRate) {
return $price - ($price * $discountRate / 100);
}
$price = 1000;
$discountRate = 10;
echo "Discounted Price: " . calculateDiscount($price,
$discountRate);
// Outputs: Discounted Price: 900
Mastering functions is essential for creating clean, reusable, and efficient PHP programs.