Introduction
Functions are thebuilding blocks of any programming language, including
PHP. They allow you to encapsulate reusable code, making your applications
more organized, maintainable, and efficient. In this session, we'll explore how
to define and use functions in PHP, examine into advanced concepts, and work
through practical examples.
3.
Understanding Functions
What isa Function?
• Definition: A block of code designed to perform a particular
task, executed when "called" by its name.
• Benefits:
• Reusability: Write once, use multiple times.
• Modularity: Break down complex problems.
• Maintainability: Easier to manage and update code.
Built-in vs. User-defined Functions
• Built-in Functions: Predefined functions provided by PHP(e.g.,
echo(), print_r(), array_merge()).
• User-defined Functions: Custom functions created by
developers to perform specific tasks.
4.
Defining and
Calling
Functions
Syntax ofa Function
• Definition Syntax:
function functionName($parameter1, $parameter2,
...) {
// Code to execute
return $value; // Optional
}
Calling a Function:
functionName($argument1, $argument2, ...);
Function
Parameters and
Arguments
• Parameters:Variables listed in the
function definition.
• Arguments: Values passed to the
function when called.
• Example with Parameters:
function greet($name) {
echo "Hello, $name!";
}
greet(“Abdi"); // Outputs: Hello, Abdi!
7.
Return Values
• Usingthe return Statement
• Purpose: Returns a value from the function to
the caller and exits the function.
• Example:
function add($a, $b) {
return $a + $b;
}
$sum = add(5, 10); // $sum is 15
echo $sum;
Variable Scope
Local andGlobal Variables
• Local Variables: Declared within a function and
accessible only within that function.
function test() {
$localVar = "I'm local";
}
• Global Variables: Declared outside functions and
accessible anywhere using the global keyword.
$globalVar = "I'm global";
function test() {
global $globalVar;
echo $globalVar;
}
13.
The static Keyword
•Purpose: Retains the variable's value
between function calls.
• Example:
function counter() {
static $count = 0;
$count++;
echo $count;
}
counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3
14.
Anonymous
Functions and
Closures
• AnonymousFunctions
• Definition: Functions without names, often used
as values.
• Example:
$greet = function($name) {
return "Hello, $name!";
};
echo $greet(“Aliya"); // Outputs: Hello, Aliya!
15.
Closures with useKeyword
• Purpose: Access variables outside of the function's scope.
• Example:
$message = "Welcome";
$greet = function($name) use ($message) {
return "$message, $name!";
};
echo $greet(“Ali"); // Outputs: Welcome, Ali!
16.
Recursive
Functions
• Understanding Recursion
•Definition: A function that calls itself.
• Use Cases: Traversing data structures (e.g., trees),
solving mathematical problems (e.g., factorial).
• Example: Calculating Factorial:
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5); // Outputs: 120
17.
Type Declarations and
ReturnTypes
Scalar Type Declarations
Syntax:
function functionName(int $param1, string $param2) {
// Code
}
Example:
function add(int $a, int $b) {
return $a + $b;
}
echo add(5, 10); // Outputs: 15
18.
Return Type Declarations
•Syntax:
function functionName($param): returnType {
// Code
}
Example:
function getGreeting(string $name): string {
return "Hello, $name!";
}
echo getGreeting(“Mohamed"); // Outputs: Hello, Mohamed!
19.
Practical Sessions
• Task:Create functions for basic arithmetic operations.
function add($a, $b) {
return $a + $b;
}
function subtract($a, $b) {
return $a - $b;
}
function multiply($a, $b) {
return $a * $b;
}
function divide($a, $b) {
if ($b == 0) {
return "Cannot divide by zero";
}
return $a / $b;
}
// Usage
echo add(10, 5); // Outputs: 15
echo divide(10, 0); // Outputs: Cannot divide by zero
20.
Practical Sessions
• Task:Create a function to sanitize and validate email addresses.
function validateEmail($email) {
$email = trim($email);
$email = stripslashes($email);
$email = htmlspecialchars($email);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
// Usage
$userEmail = " user@example.com ";
if (validateEmail($userEmail)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
21.
Working with
Arrays
• Task:Create a function to find the maximum value in an array.
function findMax(array $numbers) {
if (empty($numbers)) {
return null;
}
$max = $numbers[0];
foreach ($numbers as $number) {
if ($number > $max) {
$max = $number;
}
}
return $max;
}
// Usage
$values = [3, 7, 2, 9, 5];
echo findMax($values); // Outputs: 9
22.
Callback Functions
• Definition:Passing a function as an argument to another
function.
• Example:
function filterArray($arr, $callback) {
$result = [];
foreach ($arr as $item) {
if ($callback($item)) {
$result[] = $item;
}
}
return $result;
}
$numbers = [1, 2, 3, 4, 5];
$evenNumbers = filterArray($numbers, function($n) {
return $n % 2 == 0;
});
print_r($evenNumbers); // Outputs: Array ( [0] => 2 [1] => 4 )
23.
Questions and Exercises
•Q1: What is the difference between parameters and
arguments in functions?
• Q2: How do anonymous functions differ from regular
functions?
• Exercise: Write a function that takes a string and returns the
string reversed without using PHP's built-in strrev() function.
24.
Best Practices
• NamingConventions
i. Use meaningful names: e.g., calculateTotal(), getUserData().
ii. Consistency: Stick to a naming convention like camelCase or snake_case.
• Documentation
i. Comment your code: Explain complex logic.
ii. Use PHPDoc: For function descriptions, parameters, and return types.
/**
* Calculates the area of a circle.
*
* @param float $radius The radius of the circle.
* @return float The calculated area.
*/
function calculateArea(float $radius): float {
return pi() * pow($radius, 2);
}