Creating Functions in PHP – A Quick Guide
Learn how to define and use functions in PHP, pass parameters, return values, and follow best practices to write reusable code.
📌 What Are Functions?
Functions are blocks of reusable code that perform specific tasks. In PHP, functions help reduce repetition, organize code, and improve readability.
✍️ Defining a Simple Function
Use the function
keyword followed by a name and a pair of parentheses.
<?php
function sayHello() {
echo "Hello, world!";
}
sayHello();
?>
This outputs Hello, world!
when called.
📦 Functions with Parameters
Parameters allow you to pass values to functions.
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("Alice");
?>
Outputs: Hello, Alice!
🔁 Returning Values from Functions
Use return
to send a result back to the caller.
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(5, 7);
echo $result; // 12
?>
🛠️ Default Parameter Values
Set default values to make parameters optional.
<?php
function greetUser($name = "Guest") {
echo "Welcome, $name!";
}
greetUser(); // Welcome, Guest!
?>
🔍 Type Hinting
PHP allows you to specify expected types for parameters and return values (PHP 7+).
<?php
function multiply(int $x, int $y): int {
return $x * $y;
}
echo multiply(3, 4); // 12
?>
👻 Anonymous Functions & Closures
You can create functions without a name and assign them to variables.
<?php
$shout = function($msg) {
echo strtoupper($msg);
};
$shout("hello"); // HELLO
?>
📌 Variable Scope
Variables inside functions are local by default. Use global
to access outside variables.
<?php
$site = "MyBlog";
function showSite() {
global $site;
echo $site;
}
showSite();
?>
✅ Best Practices
- Use descriptive names like
calculateTotal()
orsendEmail()
- Keep functions short and focused on one task
- Return results instead of echoing inside functions (makes testing easier)
- Avoid using global variables inside functions unless absolutely necessary
🌍 Real-World Use Cases
- Form validation
- Database operations
- Formatting and sanitizing input
- Calculations and reports
- Email notifications
Tags: PHP functions, define function PHP, function examples PHP, PHP beginner tutorial
📘 Up next: Learn how to include and organize code across multiple PHP files using include
and require
.