Functions
Functions are one of the most important concepts in programming. They allow you to write reusable blocks of code that can be called multiple times with different inputs, making your code cleaner, more organized, and easier to maintain.
What You'll Learn
- How to define and call functions
- Function parameters and arguments
- Return values and the return statement
- Default parameter values
- Variable scope
- Type declarations in modern PHP
Defining Functions
In PHP, you define a function using the function keyword:
<?php
// Define a simple function
function greet() {
echo "Hello, World!\n";
}
// Call the function
greet();
greet(); // You can call it multiple times
Functions with Parameters
Parameters allow you to pass data into functions:
<?php
// Function with one parameter
function greetPerson($name) {
echo "Hello, $name!\n";
}
// Call with different arguments
greetPerson("Alice");
greetPerson("Bob");
greetPerson("Charlie");
// Function with multiple parameters
function introduce($name, $age, $city) {
echo "$name is $age years old and lives in $city.\n";
}
introduce("Alice", 25, "New York");
introduce("Bob", 30, "London");
Return Values
Functions can return values using the return statement:
<?php
// Function that returns a value
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo "5 + 3 = $result\n";
// Using the return value directly
echo "10 + 20 = " . add(10, 20) . "\n";
// Function with multiple return points
function getGrade($score) {
if ($score >= 90) {
return "A";
} elseif ($score >= 80) {
return "B";
} elseif ($score >= 70) {
return "C";
} elseif ($score >= 60) {
return "D";
} else {
return "F";
}
}
echo "Score 95: Grade " . getGrade(95) . "\n";
echo "Score 75: Grade " . getGrade(75) . "\n";
echo "Score 55: Grade " . getGrade(55) . "\n";
Default Parameter Values
You can provide default values for parameters:
<?php
// Function with default parameter
function greetWithTitle($name, $title = "Mr.") {
echo "Hello, $title $name!\n";
}
greetWithTitle("Smith"); // Uses default "Mr."
greetWithTitle("Smith", "Dr."); // Overrides with "Dr."
greetWithTitle("Johnson", "Ms."); // Overrides with "Ms."
// Multiple default parameters
function createUser($username, $role = "user", $active = true) {
$status = $active ? "active" : "inactive";
echo "User: $username, Role: $role, Status: $status\n";
}
createUser("alice");
createUser("bob", "admin");
createUser("charlie", "moderator", false);
Best Practice: Put parameters with default values at the end of the parameter list.
Type Declarations
Modern PHP (7.0+) supports type declarations for parameters and return types:
<?php
// Parameter type declarations
function multiply(int $a, int $b): int {
return $a * $b;
}
echo "5 * 3 = " . multiply(5, 3) . "\n";
// String type
function formatName(string $firstName, string $lastName): string {
return strtoupper($lastName) . ", " . $firstName;
}
echo formatName("John", "Doe") . "\n";
// Float type
function calculateArea(float $length, float $width): float {
return $length * $width;
}
echo "Area: " . calculateArea(5.5, 3.2) . "\n";
// Mixed return types (PHP 8.0+)
function getValue(bool $returnString) {
if ($returnString) {
return "Hello";
}
return 42;
}
echo "String: " . getValue(true) . "\n";
echo "Number: " . getValue(false) . "\n";
Variable Scope
Variables inside functions have local scope - they're only accessible within the function:
<?php
$globalVar = "I'm global";
function testScope() {
$localVar = "I'm local";
echo $localVar . "\n";
// To access global variables, use the global keyword
global $globalVar;
echo $globalVar . "\n";
}
testScope();
// echo $localVar; // This would cause an error
// Better practice: pass variables as parameters
function betterScope($value) {
return "Processing: $value";
}
echo betterScope($globalVar) . "\n";
Best Practice: Avoid using global variables. Instead, pass data as parameters and return results.
Practical Examples
Here are some real-world examples of useful functions:
<?php
// Calculate total price with tax
function calculateTotal(float $price, float $taxRate = 0.08): float {
return $price * (1 + $taxRate);
}
echo "Price $50 with 8% tax: $" . calculateTotal(50) . "\n";
echo "Price $100 with 10% tax: $" . calculateTotal(100, 0.10) . "\n";
// Validate email format
function isValidEmail(string $email): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
echo "Is 'user@example.com' valid? " . (isValidEmail("user@example.com") ? "Yes" : "No") . "\n";
echo "Is 'invalid-email' valid? " . (isValidEmail("invalid-email") ? "Yes" : "No") . "\n";
// Format currency
function formatCurrency(float $amount, string $currency = "USD"): string {
return $currency . " " . number_format($amount, 2);
}
echo formatCurrency(1234.56) . "\n";
echo formatCurrency(999.99, "EUR") . "\n";
// Generate random password
function generatePassword(int $length = 8): string {
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$password = "";
for ($i = 0; $i < $length; $i++) {
$password .= $characters[rand(0, strlen($characters) - 1)];
}
return $password;
}
echo "Random password (8 chars): " . generatePassword() . "\n";
echo "Random password (12 chars): " . generatePassword(12) . "\n";
Try It Yourself
Practice creating functions with these exercises:
<?php
// 1. Create a function that calculates the area of a rectangle
function calculateRectangleArea(float $length, float $width): float {
return $length * $width;
}
echo "Rectangle area (5x3): " . calculateRectangleArea(5, 3) . "\n";
// 2. Create a function that checks if a number is even
function isEven(int $number): bool {
return $number % 2 === 0;
}
echo "Is 4 even? " . (isEven(4) ? "Yes" : "No") . "\n";
echo "Is 7 even? " . (isEven(7) ? "Yes" : "No") . "\n";
// 3. Create a function that converts Celsius to Fahrenheit
function celsiusToFahrenheit(float $celsius): float {
return ($celsius * 9/5) + 32;
}
echo "0°C = " . celsiusToFahrenheit(0) . "°F\n";
echo "100°C = " . celsiusToFahrenheit(100) . "°F\n";
// 4. Create a function that returns the larger of two numbers
function max2(float $a, float $b): float {
return $a > $b ? $a : $b;
}
echo "Max of 5 and 10: " . max2(5, 10) . "\n";
// Try creating your own functions!
Key Takeaways
- Functions are defined with the
functionkeyword - Parameters allow you to pass data into functions
- Use
returnto send values back from functions - Default parameters provide fallback values
- Type declarations help catch errors and document your code
- Variables inside functions have local scope
- Functions make code reusable and easier to maintain
Next Steps
In the next lesson, we'll explore control flow - how to make decisions in your code using if statements, loops, and more. You'll learn how to write programs that can respond to different conditions and repeat actions.
Pro Tip: Write small, focused functions that do one thing well. This makes your code easier to test, debug, and reuse. Use descriptive function names that clearly explain what the function does. Consider adding type declarations to make your functions more robust and self-documenting.