PHP: Functions — The Basics
Functions are the basic building blocks of programming. Wrap reusable code into functions, and you level up from "writing scripts" to "building with blocks" — each function becomes a reusable piece.
1. Defining and Calling Functions
<?php
// Define a function
function greet() {
echo "Hello, World!";
}
// Call the function
greet(); // Output: Hello, World!
greet(); // You can call it repeatedly
?>
Function names are case-insensitive (but the convention is lowercase with underscores — snake_case):
GREET(); // This also works, but don't do it
2. Parameters and Return Values
Functions can receive parameters (input) and return data (output):
<?php
// A function with a parameter
function greet($name) {
return "Hello, {$name}!";
}
$msg = greet("John");
echo $msg; // Hello, John!
?>
(1) Multiple Parameters
<?php
function calculateTotal($price, $quantity, $tax = 1.0) {
return $price * $quantity * $tax;
}
echo calculateTotal(10, 3); // 30 (tax uses the default of 1.0)
echo calculateTotal(10, 3, 1.13); // 33.9 (custom tax passed in)
?>
function f($a = 1, $b) will cause an error.
3. Type Declarations (PHP 7+)
PHP 7+ supports type declarations for function parameters and return values, making your code safer:
<?php
// Parameter type declarations + return type declaration
function add(int $a, int $b): int {
return $a + $b;
}
echo add(3, 5); // 8
echo add("3", "5"); // 8 (PHP auto-converts)
// echo add("hello", 5); // TypeError!
// Other type declarations
function displayUser(string $name, int $age): void {
echo "{$name}, {$age} years old";
}
function getPrice(float $price): string {
return "$" . number_format($price, 2);
}
?>
| Type | Declaration | Notes |
|---|---|---|
| Integer | int |
Auto-converts to int |
| Float | float |
Auto-converts to float |
| String | string |
Auto-converts to string |
| Boolean | bool |
Auto-converts to bool |
| Array | array |
Must be an array |
| No return | void |
Cannot return anything |
| Nullable | ?string |
Accepts string or null |
| Union type (PHP 8+) | int|float |
Accepts int or float |
| Mixed | mixed |
Any type |
TypeError instead of silently producing strange results.
▶ Example: Practical Function with Type Declarations
Output:
[" . date("H:i:s") . "] {root} performed {value}<br>
9)
result
<?php
// Combined type declarations: union type + void + default value
function formatPrice(int|float $price, string $currency = "$"): string {
return $currency . number_format((float)$price, 2);
}
function logAction(string $user, string $action): void {
echo "[" . date("H:i:s") . "] {$user} performed {$action}<br>";
}
echo formatPrice(39.9); // $39.90
echo formatPrice(100); // $100.00
logAction("admin", "logged in"); // [14:30:45] admin performed logged in
?>
Output:
Output displayed
4. Strict Typing (strict_types)
By default, PHP's type declarations allow automatic type coercion ("3" can be passed to an int parameter). Enable strict mode and the types must match exactly:
▶ Example: Default Mode vs. Strict Mode
Output:
result
result
result
result
<?php
// Default mode: automatic type coercion
function double(int $n): int {
return $n * 2;
}
echo double("5"); // 10 ("5" is auto-converted to int 5)
// Strict mode: by the book
declare(strict_types=1);
function doubleStrict(int $n): int {
return $n * 2;
}
echo doubleStrict("5"); // TypeError! Must pass an int
echo doubleStrict(5); // 10 ✅
function greetStrict(string $name): string {
return "Hello, {$name}";
}
// echo greetStrict(123); // TypeError! A number is not a string
echo greetStrict("John"); // ✅
?>
Output:
Output displayed
declare(strict_types=1) must be the first statement in a PHP file (immediately after the <?php tag). It only affects function calls within the current file, not the file where the function is defined. For new projects, enable strict mode by default.
5. The return Statement
<?php
function getUser($id) {
// Query the database... let's pretend we found a user
if ($id <= 0) {
return null; // Invalid ID — bail out early
}
return [
"id" => $id,
"name" => "User{$id}"
];
}
$user = getUser(1);
if ($user !== null) {
echo $user["name"]; // User1
}
// void function: returns nothing
function logError(string $message): void {
// Write to the error log
error_log($message);
// Do not write return $something;
}
?>
After return, the function ends immediately. This is especially useful for guard clauses — handling exceptional cases first and returning early.
6. PHPDoc Comments
Good functions need documentation. PHPDoc is PHP's comment standard:
<?php
/**
* Calculate the total price
*
* @param float $price Unit price
* @param int $quantity Quantity purchased
* @param float $tax Tax rate (default 1.0 for tax-inclusive)
* @return float Final total price
*
* Examples:
* calculateTotal(10, 3) → 30.0
* calculateTotal(10, 3, 1.13) → 33.9
*/
function calculateTotal(float $price, int $quantity, float $tax = 1.0): float {
return $price * $quantity * $tax;
}
?>
| Tag | Purpose |
|---|---|
@param |
Parameter description (type + name + explanation) |
@return |
Return value description |
@throws |
Exceptions that may be thrown |
@var |
Variable type |
@see |
Related reference |
7. Function Naming Conventions
PHP function names follow the snake_case community standard:
// ✅ Good function names
function get_user_by_id($id) {}
function calculate_total_price($items) {}
function send_verification_email($email) {}
// ❌ Inconsistent naming
function GetUserById($id) {} // Don't use PascalCase
function getUserById($id) {} // Don't use camelCase (methods use this, not functions)
function getuserbyid($id) {} // Don't use all-lowercase-no-separators
get_ (fetch), set_ (assign), calculate_ (compute), create_ (make), delete_ (remove), validate_ (check), format_ (present).
▶ Example: Default Parameters and Nullable Types
<?php
function greet(string $name, string $greeting = "Hello", ?string $title = null): string {
$prefix = $title !== null ? $title . " " : "";
return "{$greeting}, {$prefix}{$name}!";
}
echo greet("Alice"); // Hello, Alice!
echo greet("Bob", "Hi"); // Hi, Bob!
echo greet("Carol", "Welcome", "Dr."); // Welcome, Dr. Carol!
Output:
Output displayed
❓ FAQ
void return type?void tells callers: "This function does something — don't expect a return value."strict_types to disable auto-coercion — passing the wrong type then causes an error, which is safer.return?return immediately ends the function. Your IDE will typically warn you about "unreachable code."📖 Summary
function name($param): type { return ... }defines a function- Parameters can have default values (must come after required parameters)
- Type declarations (
int,string,?string,int|float) make code safer declare(strict_types=1)enables strict mode — no auto type coercionvoidmeans no return value;returnimmediately ends the function- Function names use
snake_case— verb + noun, likeget_user_by_id - PHPDoc comments are for both humans and your IDE
📝 Exercises
- Write a function
calculateBMI($weight, $height)that takes weight (kg) and height (m), returns the BMI (weight ÷ height²), and appends an evaluation like "Underweight / Normal / Overweight / Obese." - Enable strict mode and write a function
formatCurrency(float $amount, string $symbol = "$"): stringthat formats a monetary amount. Use strict mode to ensure the amount is always a float. - Write a function
getPageUrl(string $base, int $page): stringthat builds a pagination URL. If page is 1, return just the base; otherwise append?page=N. Write PHPDoc comments for it.