PHP Functions
# Chapter 9: PHP Functions
1. Introduction
Welcome to Chapter 9! As your web applications grow, you'll find yourself writing the same code over and over. For example, validating an email address or connecting to a database. Copying and pasting code is a terrible practice—it makes your files huge and a nightmare to update. This is where Functions come in. A function is a reusable block of code that performs a specific task. In this chapter, we will learn how to create our own custom functions, pass data into them, and get results back.2. Learning Objectives
By the end of this chapter, you will be able to:- Declare and call custom PHP functions.
- Pass data into functions using Parameters/Arguments.
-
Return calculated data from a function using the
returnkeyword.
- Set default values for parameters.
- Understand variable scope inside and outside functions.
3. Function Creation and Calling
To create a function, use thefunction keyword, followed by a name, parentheses (), and curly braces {} containing the code.
To execute the function, you "call" it by writing its name followed by parentheses.
4. Function Parameters (Arguments)
Information can be passed to functions through arguments (variables inside the parentheses). This makes functions dynamic and adaptable.5. Return Values
Instead of just echoing data directly to the screen, a well-designed function usually performs a calculation and returns the result back to the main script. Use thereturn keyword for this. Once a function hits a return statement, it stops executing immediately.
6. Default Parameters
You can set a default value for a parameter. If the user calls the function without passing an argument, the default value is used.7. Variable Scope
Variables declared *outside* a function cannot be accessed *inside* the function. Variables declared *inside* a function cannot be accessed *outside*. This is called Variable Scope. It prevents your variables from accidentally overwriting each other.8. Real-World Examples
Imagine you need to format prices across an entire e-commerce site. Instead of repeating the formatting code, create a function.9. Output Explanations
In the pricing example, we pass199.5 into formatPrice(). The function uses a built-in PHP function number_format() to ensure there are exactly two decimal places (199.50), concatenates a dollar sign, and returns the string "$199.50". The main script then echoes the returned string.
10. Common Mistakes
-
Forgetting the
returnstatement: If your function calculates a total but forgets toreturnit, calling the function will result inNULL.
- Calling a function before it exists? Actually, PHP is smart! You can call a function at the top of the file even if it is defined at the bottom. But you cannot call a function that is misspelled.
- Missing Required Arguments: If a function expects 2 parameters and has no defaults, calling it with only 1 parameter will trigger a fatal error.
11. Best Practices
-
Do One Thing: A function should do exactly ONE specific task. Don't write a
processUser()function that validates, saves to the database, sends an email, and echoes HTML. Break those into 4 separate functions!
-
Naming Conventions: Use clear, action-oriented verbs.
calculateTotal(),getUser(),sendEmail().
-
Return, don't Echo: Functions should generally
returndata so the main script can decide whether to echo it, save it, or pass it to another function.
12. Exercises
-
1.
Create a function called
multiply()that takes two numbers, multiplies them, and returns the result.
- 2. Call your function, store the result in a variable, and echo it.
- 3. Create a function with a default parameter for a user's role (defaulting to "Guest").
13. Mini Project: BMI Calculator
Task: Build a reusable function to calculate a Body Mass Index (BMI) and another function to determine the health category.14. Coding Challenges
Challenge 1: Write a function calledisAdult($age) that returns boolean true if the age is 18 or older, and false if it is not. Test it with an if statement.
15. MCQs with Answers
1. Which keyword is used to send data back from a function? A) echo B) send C) return D) export *Answer: C*2. Can a function access a variable that was declared outside of it (by default)?
A) Yes, all variables are global.
B) No, due to variable scope constraints.
C) Only if the variable is a string.
D) Only if the function uses a while loop.
*Answer: B*
3. What happens if a function is called without an argument for a parameter that has a default value? A) A fatal error occurs. B) The script ignores the function. C) The parameter becomes NULL. D) The default value is used. *Answer: D*
16. Interview Questions
Q: Explain Variable Scope in PHP. *A:* Scope refers to the context in which a variable is defined and can be accessed. In PHP, variables defined outside a function have Global scope and cannot be accessed inside functions. Variables defined inside a function have Local scope and cannot be accessed outside. You can pass data into a function via arguments to cross this boundary.Q: Why is it better for a function to return a value rather than echo it directly?
*A:* Reusability. If a function echoes output directly, you can never use that function to just calculate a value quietly in the background or save it to a database—it will always forcefully print to the screen. Returning the value gives the caller full control over what to do with the data.
17. FAQs
Q: Are there built-in functions in PHP? *A:* Yes! Thousands of them.echo, print, vardump, numberformat, and round are all built-in functions. You are just learning how to create your own!
18. Summary
Functions are the building blocks of clean, organized applications. You learned how to define functions, pass dynamic data to them via parameters, set default parameters, and safely return results using thereturn keyword. You also grasped the critical concept of variable scope.
19. Next Chapter Recommendation
Currently, a variable can only hold one single piece of data. But what if we have a list of 100 users? Creating 100 variables ($user1, $user2) is impossible. In Chapter 10: PHP Arrays, we will learn how to store lists and complex data structures inside a single powerful variable!