Defining Functions
Declaring functions, type-hinting parameters and return values, and passing by value vs. by reference.
2 min read
Functions in PHP are declared with the function keyword and can optionally declare types for both their parameters and their return value.
A basic function
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Amara");return sends a value back to the caller and immediately exits the function — any code after return in the same execution path never runs.
Type hints
<?php
function calculateTotal(float $price, int $quantity): float {
return $price * $quantity;
}
echo calculateTotal(9.99, 3);Adding float, int, string, bool, array, or a class name before a parameter tells PHP (and anyone reading the signature) what type is expected; : float after the parentheses declares the return type. Without declare(strict_types=1) (covered in the type juggling lesson), PHP will still try to coerce a mismatched argument to the declared type rather than rejecting it outright.
Default parameter values
<?php
function greet($name, $greeting = "Hello") {
return "$greeting, $name!";
}
echo greet("Amara"); // "Hello, Amara!"
echo greet("Amara", "Welcome"); // "Welcome, Amara!"A parameter with a default value becomes optional — omit it in the call and PHP uses the default. Any parameter with a default must come after all parameters without one, in the parameter list.
Nullable and union types
<?php
function findUser(?int $id): ?string {
if ($id === null) {
return null;
}
return "User #$id";
}
function formatValue(int|string $value): string {
return (string) $value;
}A ? before a type (?int) means "this type, or null." A | between types (int|string) declares a union type — the parameter or return value can be either. Both were added in relatively recent PHP versions and are now standard in modern type-hinted code.
Passing by value vs. by reference
<?php
function double($number) {
$number *= 2;
}
function doubleByRef(&$number) {
$number *= 2;
}
$x = 5;
double($x);
echo $x; // still 5 — a copy was modified inside the function
doubleByRef($x);
echo $x; // 10 — the original variable was modifiedBy default, PHP passes scalar values (numbers, strings, booleans) by value — the function receives a copy, and changes inside it don't affect the caller's variable. Prefixing a parameter with & passes it by reference instead, letting the function modify the caller's original variable directly. Arrays and objects behave a bit differently under the hood (objects are always handled via an internal reference to the same object, even without &), which the object-oriented lessons revisit.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.