PHP Lesson 5: Functions (Building Reusable Code Blocks)
Welcome back! As your programs grow, you'll find yourself performing the same tasks repeatedly (e.g., calculating sales tax, validating a user's input, or formatting a date). Functions allow you to bundle these tasks into a single, reusable unit, avoiding repetition.
1. What is a Function?
A function is a block of code written to perform a specific task. Once defined, you can execute that code block anytime and anywhere in your program simply by calling the function's name.
2. Defining Your Own Function
In PHP, you define a function using the function keyword, followed by the function's name and parentheses ().
Basic Function Example
<?php
// 1. Function Definition
function sayHello() {
echo "Hello, welcome to my PHP lesson! <br>";
}
// 2. Calling the function (Executing the code block)
sayHello();
sayHello();
// Output:
// Hello, welcome to my PHP lesson!
// Hello, welcome to my PHP lesson!
?>
3. Parameters and Arguments
Functions become truly powerful when they can accept information from the outside.
Parameters: The placeholders (variables) defined in the function definition (inside the parentheses).
Arguments: The actual values you pass to the function when you call it.
Function with Parameters
<?php
// $name is the parameter
function greetUser($name) {
echo "Good afternoon, $name! How can I help you? <br>";
}
// "Sarah" is the argument passed to the function
greetUser("Sarah");
// "Mark" is a different argument
greetUser("Mark");
// Output:
// Good afternoon, Sarah! How can I help you?
// Good afternoon, Mark! How can I help you?
?>
4. Returning Values
Most functions don't just echo output; they process data and give a result back to the code that called them. This is done using the return keyword.
When PHP hits the return statement, the function immediately stops execution, and the specified value is sent back.
Function with Return Value
<?php
// This function calculates 15% tax on an amount and returns the result.
function calculateTax($subtotal) {
$taxRate = 0.15;
$taxAmount = $subtotal * $taxRate;
return $taxAmount; // Send the calculated value back
}
$orderTotal = 150;
// 1. Call the function and store the returned value in a new variable
$taxDue = calculateTax($orderTotal);
// 2. Use the returned value in further calculations
$finalPrice = $orderTotal + $taxDue;
echo "Subtotal: $" . $orderTotal . "<br>";
echo "Tax Due: $" . $taxDue . "<br>";
echo "Final Price: $" . $finalPrice;
// Output:
// Subtotal: $150
// Tax Due: $22.5
// Final Price: $172.5
?>
5. Built-in PHP Functions
Before writing your own function, always check if PHP already has a built-in one! PHP has thousands of functions for common tasks, which you've already seen examples of:
date(): Formats the current date and time (Lesson 1).count(): Returns the number of elements in an array.strlen(): Returns the length of a string.strtoupper()/strtolower(): Converts a string to uppercase/lowercase.
<?php
$text = "Learning PHP is fun!";
echo "Original length: " . strlen($text) . "<br>";
echo "Uppercase: " . strtoupper($text);
?>
🚀 Your Fifth Challenge!
Create a function called isAdult that takes one parameter, $age.
Inside the function, use an
ifstatement to check if$ageis greater than or equal to18.The function should
returnthe boolean valueTRUEif the person is 18 or older, andFALSEotherwise.Call the function with a test age (e.g.,
16) and use the returned value in anifstatement outside the function toecho"Welcome!" or "Access Denied!".
Congratulations! You now understand the five core pillars of programming: Output, Variables, Data Structures (Arrays), Control Flow (If/Loops), and Reusability (Functions). You are ready to start building simple web applications!
Comments
Post a Comment
Add your comment here.