How to Define a Custom Function in PHP
This article provides a straightforward guide on how to create and use custom functions in PHP. You will learn the basic syntax for declaring a function, how to pass arguments to it, how to return values, and how to define default parameter values to write cleaner, more reusable code.
Basic Syntax of a PHP Function
To define a custom function in PHP, you use the function
keyword, followed by the name of the function, a set of parentheses
(), and a block of code enclosed in curly braces
{}.
Function names are case-insensitive, but it is best practice to use camelCase or underscores (snake_case) to keep your code readable. A function name must start with a letter or an underscore, not a number.
<?php
// Defining a basic function
function greetUser() {
echo "Hello, welcome to PHP!";
}
// Calling the function
greetUser();
?>Passing Arguments to a Function
You can pass information into a function using arguments. Arguments are specified inside the parentheses after the function name. You can add as many arguments as you want, separated by commas.
<?php
// Function with one argument
function greetByName($name) {
echo "Hello, " . $name . "!";
}
greetByName("Alice"); // Outputs: Hello, Alice!
greetByName("Bob"); // Outputs: Hello, Bob!Returning Values from a Function
To make a function return a value instead of outputting it directly,
use the return statement. This allows you to store the
output of the function in a variable for later use.
<?php
// Function that returns a value
function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$result = addNumbers(5, 10);
echo $result; // Outputs: 15Setting Default Parameter Values
You can specify a default value for a parameter. If the function is called without that argument, PHP will use the default value.
<?php
// Function with a default parameter
function setHeight($minHeight = 50) {
echo "The height is : $minHeight <br>";
}
setHeight(350); // Outputs: The height is : 350
setHeight(); // Outputs: The height is : 50 (uses default)Type Declarations (PHP 7+)
In modern PHP, you can specify the expected data type for arguments and return values. This prevents unexpected data types from causing errors in your application.
<?php
// Function with strict type declarations
function multiply(int $a, int $b): int {
return $a * $b;
}
echo multiply(5, 4); // Outputs: 20