PHP Functions — Parameter Order Change Breaks Checkout
Swapped price and tax parameters in calculateTotal() silently outputs zero in checkout.
- Functions are named blocks of reusable code defined with the
functionkeyword. - Parameters act as placeholders; arguments are the real values passed during a call.
- Use
returnto hand back a result — far more flexible thanechoinside the function. - Variables outside a function are invisible inside unless passed as arguments.
- Always capture return values or they silently vanish as NULL.
Think of a PHP function like a vending machine. You put in your money (the input), press a button (call the function), and out comes your snack (the output). The machine handles everything in between — you don't need to know how it works inside, just how to use it. Once the vending machine exists, anyone can use it, as many times as they want, without rebuilding it each time. That's exactly what a function does in PHP.
Every real-world PHP application — from a login form to an e-commerce cart — is built on functions. They're the backbone of organised, maintainable code. Without them, you'd be writing the same logic over and over in dozens of places, and the moment something changes (a tax rate, a validation rule, a greeting message), you'd have to hunt down every copy and fix each one manually. That's where bugs are born.
Functions solve the 'write once, use everywhere' problem. You package a piece of logic into a named block, and then call that block by name whenever you need it. The code stays in one place, so a fix in one spot fixes it everywhere. This is one of the most fundamental ideas in all of programming, and PHP makes it beautifully simple to get started.
By the end of this article you'll know how to define your own PHP functions, pass data into them using parameters, get data back out using return values, set sensible defaults, and understand the difference between built-in and user-defined functions. You'll also walk away knowing the mistakes that trip up almost every beginner — and exactly how to dodge them.
What a PHP Function Actually Is (And Why You Need One)
A function is a named block of code that sits quietly until you call it. The moment you call it, PHP executes every line inside it, then hands control back to wherever you called it from.
PHP ships with hundreds of built-in functions — strlen() counts characters in a string, array_push() adds items to an array, date() formats a timestamp. You've been using other people's functions without even realising it.
But the real power is writing your own. Imagine you're building a website that greets every user by name. Without a function, you'd write that greeting logic on every page. With a function, you write it once, give it a name like greetUser(), and call that name wherever you need it.
This principle has a name: DRY — Don't Repeat Yourself. Functions are the primary tool for achieving it. They also make your code readable. A well-named function tells a future developer (or future you) exactly what a block of code does, without them having to read every line of it.
GreetUser() and GREETUSER() all call the same function. That said, always use the exact name you defined as a habit; it keeps your code readable and consistent.Passing Data Into Functions — Parameters and Arguments
A function with no input is useful, but a function that can accept data is powerful. This is where parameters come in.
A parameter is a variable you declare inside the function's parentheses. It acts as a placeholder — a slot waiting to receive a value. When you actually call the function and pass a value into that slot, that value is called an argument.
Here's the analogy: a parameter is like a labelled inbox on a desk ('place name here'). An argument is the actual piece of paper you drop into that inbox. The function then uses whatever you dropped in.
You can define multiple parameters by separating them with commas. The order matters — the first argument you pass maps to the first parameter, the second argument maps to the second parameter, and so on.
PHP also lets you define default parameter values. If the caller doesn't pass an argument, the parameter falls back to its default. This is incredibly handy for optional settings — think of it as a form field that's pre-filled but can be changed.
Getting Data Back Out — Return Values
So far our functions print things directly. That's fine for simple output, but most of the time you want a function to calculate or process something and hand the result back to you so you can decide what to do with it next. That's what return does.
Think of return like a function handing you a receipt. You gave it your payment details (arguments), it processed the transaction (ran the logic), and now it's giving you something back (the return value) that you can hold onto, print, store in a variable, or pass into another function.
Once PHP hits a return statement, the function stops immediately. Anything after return in the same function is ignored. This makes return useful for early exits too — you'll see that pattern a lot in validation functions.
A function that doesn't have a return statement returns NULL by default. That's not an error, it just means the function produces no usable output beyond any side effects (like printing to the screen).
@ if intentional.return to hand data back — it gives the caller control over output.return is present can cause subtle bugs if the result is used in expressions.Variable Scope — Why Your Variables 'Disappear' Inside Functions
This is the concept that surprises almost every PHP beginner, so pay close attention. In PHP, variables defined outside a function are NOT automatically available inside it. Functions have their own private scope — like a room with a closed door.
If you create $username = 'Alice' at the top of your script and try to use $username inside a function without passing it in, PHP won't find it. The function's room has no window into the outside world by default.
There are three ways to get data into a function's scope: pass it as an argument (the recommended way), use the global keyword (rarely recommended, mostly a code smell), or use a closure with use() (an advanced topic). For now, stick to passing arguments — it makes your functions predictable and testable.
The reverse is also true: a variable you create inside a function disappears the moment the function finishes. It doesn't leak out into the rest of your script. This isolation is actually a feature, not a bug — it means functions can't accidentally overwrite your other variables.
global except for legacy code.Type Declarations and Return Types – Writing Self-Documenting Functions
PHP 7+ and especially PHP 8 made it possible to declare the type of each parameter and the type of the return value. This isn't just documentation — it forces PHP to enforce the types at runtime, catching bugs before they reach production.
When you write function greet(string $name): string, you tell PHP: 'I expect a string as input, and I guarantee I'll return a string.' If someone passes an array or the function accidentally returns an integer, PHP throws a TypeError immediately.
Type declarations make your function contracts explicit. Anyone reading or using your function knows exactly what to pass and what to expect. Combined with strict mode (declare(strict_types=1);), even implicit type coercions are caught.
Common types include: int, float, string, bool, array, callable, iterable, object, and class/interface names. Union types (int|string) and nullable types (?int) give you even more flexibility.
'0' and silently produce incorrect results.declare(strict_types=1) to disable coercion and enforce strict types per file.Parameter Order Change Breaks Checkout
calculateTotal($price, $tax) became calculateTotal($tax, $price). All existing calls passed arguments in the original order, leading to misuse of values.calculateTotal(tax: $rate, price: $subtotal)), or wrap parameters into an associative array. Also update all callers to match the new order.- Parameter order is part of the public contract — treat it as immutable once callers exist.
- Named arguments eliminate positional order dependencies and are easier to read.
- Unit tests should catch swapped arguments if values are distinct enough.
return statement on every branch? If not, default is NULL. Add explicit return for all cases.global keyword (but prefer parameters).return instead of echo. Capture the return value in a variable and then print it.Call to undefined function errorif blocks aren't available until the block runs.Key takeaways
Common mistakes to avoid
3 patternsCalling a function before it's defined in conditional code
Forgetting to capture the return value
$result = myFunction();. Then use $result as needed.Assuming outer variables are available inside a function
Interview Questions on This Topic
What is the difference between a parameter and an argument in PHP, and can you give a concrete example of each?
php
function greet($name) { // $name is a parameter
echo "Hello, $name";
}
greet('Alice'); // 'Alice' is an argument
``Frequently Asked Questions
That's PHP Basics. Mark it forged?
5 min read · try the examples if you haven't