Functions in PHP are reusable blocks of code that perform specific tasks. They help make code modular, efficient, and easier to debug. This lesson will explore defining and calling functions, working with parameters and return values, and understanding variable scope and global variables.
6.1 Defining and Calling Functions
What is a Function?
- A function is a block of code that executes when called.
- Functions can accept inputs (parameters) and return outputs.
Syntax
function functionName() {
// Code to be executed
}
?>
Defining a Function
function sayHello() {
echo “Hello, World!”;
}
?>
Calling a Function
sayHello(); // Outputs: Hello, World!
?>
Example: Function with a Task
function displayDate() {
echo “Today’s date is ” . date(“Y-m-d”) . “
“;
}
displayDate(); // Outputs today’s date
displayDate(); // Can be reused
?>
6.2 Function Parameters and Return Values
Parameters
- Parameters are variables passed to a function when it is called.
- Syntax:
function functionName($param1, $param2) {
// Code that uses $param1 and $param2
}
?>
Example: Function with Parameters
function greet($name) {
echo “Hello, $name!
“;
}
greet(“Alice”); // Outputs: Hello, Alice!
greet(“Bob”); // Outputs: Hello, Bob!
?>
Default Parameter Values
- Parameters can have default values.
- Example:
function greet($name = “Guest”) {
echo “Hello, $name!
“;
}
greet(); // Outputs: Hello, Guest!
greet(“Alice”); // Outputs: Hello, Alice!
?>
Return Values
- A function can return a value using the
return
keyword. - Syntax:
function functionName($param) {
return $value;
}
?>
Example: Function with Return Value
function add($a, $b) {
return $a + $b;
}
$result = add(5, 10); // Returns 15
echo “Sum: $result
“;
?>
Example: Function with Multiple Parameters and Return
function calculateArea($length, $width) {
return $length * $width;
}
$area = calculateArea(5, 10); // Returns 50
echo “Area: $area
“;
?>
Combining Parameters and Return Values
function calculateDiscount($price, $discountRate) {
$discount = $price * ($discountRate / 100);
return $price – $discount;
}
$finalPrice = calculateDiscount(100, 10); // Returns 90
echo “Final Price: $finalPrice
“;
?>
6.3 Variable Scope and Global Variables
What is Variable Scope?
Scope determines where a variable can be accessed. PHP has:
- Local Scope
- Global Scope
- Static Variables
Local Scope
- Variables defined inside a function are local to that function.
- Example:
function testScope() {
$localVar = “I’m local!”;
echo $localVar; // Accessible here
}
testScope(); // Outputs: I’m local
// echo $localVar; // Error: Undefined variable
?>
Global Scope
- Variables declared outside functions are global.
- Example:
$globalVar = “I’m global!”;
function testGlobal() {
// echo $globalVar; // Error: Undefined variable
}
testGlobal();
?>
Accessing Global Variables Inside Functions
- Use the
global
keyword or$GLOBALS
array. - Example:
$x = 5;
$y = 10;
function sumGlobal() {
$sum = $GLOBALS[‘x’] + $GLOBALS[‘y’];
echo “Sum: $sum
“;
}
sumGlobal(); // Outputs: Sum: 15
?>
Static Variables
- Static variables retain their value between function calls.
- Example:
function counter() {
static $count = 0;
$count++;
echo “Count: $count
“;
}
counter(); // Outputs: Count: 1
counter(); // Outputs: Count: 2
counter(); // Outputs: Count: 3
?>
Activities and Exercises
- Defining and Calling Functions:
- Write a function that takes your name as input and outputs “Welcome, [Name]!”
- Function Parameters:
- Create a function to calculate the perimeter of a rectangle. It should take length and width as inputs.
- Return Values:
- Write a function that calculates the compound interest and returns the final amount.
- Global Variables:
- Write a script where a global variable tracks the total sales of a shop across multiple function calls.
- Static Variables:
- Create a function that counts how many times it has been called.
Assignment
Write a PHP script that:
- Defines a function
calculateGrade
to calculate a student’s grade based on their score.- Parameters:
score
- Return: Grade (
A
,B
,C
, orF
based on the score) - Criteria:
- 90 and above:
A
- 75–89:
B
- 50–74:
C
- Below 50:
F
- 90 and above:
- Parameters:
- Accepts a student’s score as input and displays their grade.
Summary
In this lesson, you learned how to:
- Define and call functions.
- Work with function parameters and return values.
- Understand variable scope, global variables, and static variables.
These concepts form the foundation for writing clean and modular PHP code. Let me know if you’d like additional examples or exercises!
Leave a Reply