Skip to Content
Course content

11: Defining and Calling Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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: $originalPrice and $isMember (a boolean).
  • If $isMember is true, apply a 20% discount to the price.
  • If $isMember is false, 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)
Rating
0 0

There are no comments for now.

to be the first to leave a comment.