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
<?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):

PHP
GREET();  // This also works, but don't do it

2. Parameters and Return Values

Functions can receive parameters (input) and return data (output):

PHP
<?php
// A function with a parameter
function greet($name) {
    return "Hello, {$name}!";
}

$msg = greet("John");
echo $msg;  // Hello, John!
?>

(1) Multiple Parameters

PHP
<?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)
?>
💡 Tip: Parameters with default values must come after parameters without default values. 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
<?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
💡 Tip: When writing new code, always add type declarations. They make your code's intent clearer and catch bugs early — if the caller passes the wrong type, you get a TypeError instead of silently producing strange results.

▶ Example: Practical Function with Type Declarations

Output:

TEXT 📖 Display only
[" . date("H:i:s") . "] {root} performed {value}<br>
9)
result
PHP
<?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:

TEXT 📖 Display only
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:

TEXT 📖 Display only
result
result
result
result
PHP
<?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:

TEXT 📖 Display only
Output displayed
💡 Tip: 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
<?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
<?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
💡 Tip: PHPDoc isn't just for humans — VS Code's Intelephense extension reads it to provide autocomplete and type hints. Well-written PHPDoc turns your IDE into an intelligent assistant.


7. Function Naming Conventions

PHP function names follow the snake_case community standard:

PHP
// ✅ 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
💡 Tip: Verb + noun: get_ (fetch), set_ (assign), calculate_ (compute), create_ (make), delete_ (remove), validate_ (check), format_ (present).

▶ Example: Default Parameters and Nullable Types

PHP
<?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!
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed

❓ FAQ

Q When should I use the void return type?
A When a function performs an action without returning data — e.g., outputting a page, writing a log, sending an email, modifying global state. void tells callers: "This function does something — don't expect a return value."
Q What's the difference between type declarations and type conversion?
A Type declarations in the function signature say "I expect this type." PHP automatically coerces types at call time. Enable strict_types to disable auto-coercion — passing the wrong type then causes an error, which is safer.
Q Can I write code after return?
A You can, but it won't execute. return immediately ends the function. Your IDE will typically warn you about "unreachable code."

📖 Summary

📝 Exercises

  1. 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."
  2. Enable strict mode and write a function formatCurrency(float $amount, string $symbol = "$"): string that formats a monetary amount. Use strict mode to ensure the amount is always a float.
  3. Write a function getPageUrl(string $base, int $page): string that builds a pagination URL. If page is 1, return just the base; otherwise append ?page=N. Write PHPDoc comments for it.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏