PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
11: Defining and Calling Functions
Imagine you're running a busy coffee shop. Every time a customer orders a latte, you don't sit them down and explain the entire chemistry of milk frothing and the history of espresso beans. You don't even re-read the manual on how to use the machine. Instead, you have a "process" for a latte. You just trigger that process: grab a cup, steam the milk, pull the shot, combine. You've essentially created a mental shortcut. You call it "Make Latte," and your brain executes a series of pre-defined steps without you having to rethink the logic every single time.
In PHP, a function is exactly that: a named shortcut for a block of code. Instead of writing the same ten lines of logic every time you need to format a price or validate an email, you wrap that logic in a function and call it by name whenever you need it.
Creating Your Own Shortcuts
To define a function, you use the function keyword, give it a name, and wrap the logic in curly braces. Let's look at a real scenario. Suppose you're building a store and you need to calculate the final price of an item after adding sales tax. You'll be doing this in dozens of places across your site, so writing the math over and over is just asking for a typo to ruin your day.
function calculateTotalWithTax($price, $taxRate) {
$taxAmount = $price * $taxRate;
return $price + $taxAmount;
}
Notice a few things here. First, the name calculateTotalWithTax tells anyone reading the code exactly what's happening. Second, I've included $price and $taxRate inside the parentheses. These are called parameters. Think of them as empty slots that the function expects you to fill when you actually use it.
Triggering the Action
Defining the function is like writing the recipe; it doesn't actually do anything until you call it. To execute the code inside, you use the function name followed by parentheses containing the actual values (arguments) you want to pass in.
$shirtPrice = 25.00;
$stateTax = 0.07;
// Here is where we "call" the function
$finalPrice = calculateTotalWithTax($shirtPrice, $stateTax);
echo "The total cost is $" . $finalPrice; // Outputs: The total cost is $26.75
I've assigned the result of the function to $finalPrice. This works because the function used the return keyword. This is a crucial distinction I want you to grasp early.
The Return vs. Echo Trap
I see a lot of beginners use echo inside their functions to show a result. While that works for a quick test, it's usually a bad move in a real application. If you echo inside a function, you're forcing the result to be printed to the screen immediately. You can't use that value for further calculations, you can't save it to a database, and you can't change how it's formatted later.
By using return, the function hands the value back to the part of the program that called it. It's like the coffee machine handing you the cup; now you can decide if you want to add sugar to it, put it in a bag for a customer, or just throw it away. return gives you that flexibility.
Handling Optional Inputs
Sometimes, you want a function to have a "default" behavior if the user doesn't provide a specific value. PHP lets you assign a default value to a parameter. This is incredibly handy for settings that rarely change.
function formatCurrency($amount, $symbol = "$") {
return $symbol . number_format($amount, 2);
}
echo formatCurrency(100); // Outputs: $100.00 (uses default)
echo formatCurrency(100, "€"); // Outputs: €100.00 (overrides default)
I personally love this pattern because it keeps your function calls clean. You only pass the second argument when you actually need something different from the norm.
📋 Practical Task
Build a Member Discount Calculator
You are building a checkout system for a membership site. You need to create a function that calculates the final price of a product based on whether the user is a member or not.
Requirements:
- Create a function named
applyDiscount. - The function should take two parameters:
$originalPriceand$isMember(a boolean). - If
$isMemberistrue, apply a 20% discount to the price. - If
$isMemberisfalse, the price remains the same. - The function must return the final price, not echo it.
Test your code with these two scenarios:
// Scenario 1: Member buying a $100 item (Should return 80)
// Scenario 2: Non-member buying a $100 item (Should return 100)There are no comments for now.