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
Defining a Function
Calling a Function
Example: Function with a Task
6.2 Function Parameters and Return Values
Parameters
- Parameters are variables passed to a function when it is called.
- Syntax:
Example: Function with Parameters
Default Parameter Values
- Parameters can have default values.
- Example:
Return Values
- A function can return a value using the
return
keyword. - Syntax:
Example: Function with Return Value
Example: Function with Multiple Parameters and Return
Combining Parameters and Return Values
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:
Global Scope
- Variables declared outside functions are global.
- Example:
Accessing Global Variables Inside Functions
- Use the
global
keyword or$GLOBALS
array. - Example:
- Example using
$GLOBALS
:
Static Variables
- Static variables retain their value between function calls.
- Example:
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