PHP Functions
What are Functions?
Section titled “What are Functions?”Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more modular. PHP provides both built-in functions and the ability to create custom functions.
Declaring Functions
Section titled “Declaring Functions”Functions are declared using the function keyword:
function greet() { echo "Hello, World!";}
greet(); // Hello, World!Naming Rules
Section titled “Naming Rules”// Valid function namesfunction sayHello() { }function say_hello() { }function _privateFunction() { }
// Invalid: Cannot start with number or contain hyphens// function 2sayHello() { }// function say-hello() { }Parameters
Section titled “Parameters”Functions can accept parameters to make them more flexible.
Basic Parameters
Section titled “Basic Parameters”function greetUser($name) { echo "Hello, $name!";}
greetUser("John"); // Hello, John!Default Values
Section titled “Default Values”function greetUser($name = "Guest", $greeting = "Hello") { echo "$greeting, $name!";}
greetUser(); // Hello, Guest!greetUser("John", "Hi"); // Hi, John!Pass by Reference
Section titled “Pass by Reference”By default, functions receive a copy of the variable. Use & to modify the original:
function increment(&$number) { $number++;}
$value = 5;increment($value);echo $value; // 6Variable-Length Arguments
Section titled “Variable-Length Arguments”The splat operator (...) collects arguments into an array:
function sumNumbers(...$numbers) { return array_sum($numbers);}
echo sumNumbers(1, 2, 3, 4, 5); // 15Named Arguments (PHP 8.0+)
Section titled “Named Arguments (PHP 8.0+)”Specify arguments by name to skip optional parameters:
function createUser($name, $email, $age = null, $active = true) { return ['name' => $name, 'email' => $email, 'age' => $age, 'active' => $active];}
$user = createUser(name: "John", email: "john@example.com", active: false);Type Hints
Section titled “Type Hints”Type hints enforce parameter and return types. If you pass a value of the wrong type, PHP throws a TypeError at runtime and the function will not execute.
function createUser(string $name, int $age, bool $active = true): array { return ['name' => $name, 'age' => $age, 'active' => $active];}
createUser("John", 25); // WorkscreateUser("John", "twenty"); // TypeError: Argument #2 must be of type intNullable Types
Section titled “Nullable Types”Use ? to allow null:
function findUser(?int $id): ?array { if ($id === null) { return null; } return ['id' => $id, 'name' => 'John'];}Union Types (PHP 8.0+)
Section titled “Union Types (PHP 8.0+)”Accept multiple types:
function process(int|float $number): int|float { return $number * 2;}Common Type Hints
Section titled “Common Type Hints”| Type | Description |
|---|---|
string, int, float, bool | Scalar types |
array | Array type |
object | Any object |
callable | Callable (function/closure) |
mixed | Any type (PHP 8.0+) |
void | No return value |
Return Values
Section titled “Return Values”Basic Returns
Section titled “Basic Returns”function multiply($a, $b) { return $a * $b;}
echo multiply(4, 5); // 20Returning Arrays
Section titled “Returning Arrays”function getUserData($id) { return [ 'id' => $id, 'name' => 'John Doe', 'email' => 'john@example.com' ];}
$user = getUserData(1);echo $user['name']; // John DoeEarly Returns
Section titled “Early Returns”function validateAge($age) { if ($age < 0) { return "Age cannot be negative"; } return "Valid age";}Static Variables
Section titled “Static Variables”Static variables retain their value between function calls:
function countCalls() { static $count = 0; $count++; return $count;}
echo countCalls(); // 1echo countCalls(); // 2echo countCalls(); // 3For more on variable scope (global, local, superglobals), see Variables.