Functions are one of the most important building blocks in PHP. They allow you to group blocks of code into reusable, organized, and modular units.
A well-structured PHP program relies heavily on functions to avoid repetition, improve readability, and simplify debugging.
A function definition tells PHP what the function does, what parameters it accepts, and what value it returns.
What Is a Function?
A function in PHP is a block of code designed to perform a specific task.
You can define it once and call it multiple times anywhere in your program.
PHP has two types of functions:
- Built-in functions (like
strlen(),date(),var_dump()) - User-defined functions (created by you)
Syntax for Defining a Function
function functionName() {
// Code to be executed
}
Rules:
- Function names are not case-sensitive
- Must start with a letter or underscore
- Cannot start with a number
Example:
function greet() {
echo "Welcome to PHP!";
}
Calling a Function
Once defined, you can call the function anywhere in your script:
greet(); // Outputs: Welcome to PHP!
Functions with Parameters
Functions can accept arguments, making them flexible and dynamic.
Example with One Parameter
function greetUser($name) {
echo "Hello, $name!";
}
greetUser("Sagar");
Example with Multiple Parameters
function add($a, $b) {
return $a + $b;
}
echo add(10, 20); // 30
Default Parameter Values
You can assign default values to function parameters:
function welcome($name = "Guest") {
echo "Welcome, $name!";
}
welcome(); // Welcome, Guest!
welcome("Sagar"); // Welcome, Sagar!
Returning Values
Functions can return values using the return statement.
function multiply($x, $y) {
return $x * $y;
}
$result = multiply(5, 3);
echo $result; // 15
Variable Scope Inside Functions
Variables declared inside a function have local scope.
function demo() {
$x = 10;
}
echo $x; // Error: undefined
To access global variables inside a function, you must use:
global keyword
$site = "Savanka";
function showSite() {
global $site;
echo $site;
}
showSite();
Functions with Return Type (PHP 7+)
You can specify the type of value a function should return:
function subtract(int $a, int $b): int {
return $a - $b;
}
echo subtract(10, 3); // 7
Anonymous Functions (Closures)
PHP allows creating unnamed functions:
$greet = function($name) {
echo "Hello, $name!";
};
$greet("Sagar");
Best Practices
- Use meaningful function names.
- Keep functions short and focused on a single task.
- Use parameters and return values instead of global variables.
- Use type declarations for cleaner, safer code.
- Reuse functions to avoid code duplication.
External Reference:
🔗 https://www.php.net/manual/en/
View Other Articles About PHP:
🔗 http://savanka.com/category/learn/php/