Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. Function Definition (function)

Function Definition (function)

A function is a mechanism for giving a name to a set of processing steps so they can be reused. In『PHP』functions are defined with the『function』keyword, and default argument values, variadic arguments, and type declarations can be combined to write safe, readable code.

Syntax

// Basic function definition
function functionName($arg1, $arg2) {
	// processing
	return returnValue;
}

// Argument with default value
function functionName($param = defaultValue) {
	// $param uses the default value when omitted
}

// Type declarations (argument types and return type)
function functionName(type $param): returnType {
	// ...
}

// Variadic arguments (spread syntax)
function functionName(...$args) {
	// $args is received as an array
}

Syntax and Features Reference

Syntax / FeatureDescription
functionKeyword for defining a function. A defined function can be called from anywhere within the file.
returnEnds the function and returns a value to the caller. Omitting the value returns『null』.
Default valueSpecifies the value to use when an argument is omitted, written with『=』. Arguments with default values must always be placed at the end of the argument list.
Type declaration (argument)Writing a type name before an argument restricts the type of values that can be passed. A type mismatch causes an error.
Return type declarationWriting『: type』after the closing parenthesis of the argument list declares the return type.
Variadic arguments (...)Prefixing an argument name with『...』allows any number of arguments to be received together as an array.
declare(strict_types=1)Written at the top of the file, this enables strict type checking. When a type does not match, no implicit conversion is performed and an error is raised immediately.

Common Type Declarations

Type nameDescription
intInteger type.
floatFloating-point number type.
stringString type.
boolBoolean type (true / false).
arrayArray type.
?typeNullable type. Accepts the specified type or null. Example:『?string』accepts a string or null.
voidUsed only as a return type. Declares that the function returns no value.
mixedAccepts any type. Used when no type restriction is applied.

Sample Code

function_basic.php
<?php
// Basic function definition and call
// Returns a string combining an Evangelion pilot name and unit number

function formatPilot(string $pilotName, int $unitNumber): string {
	return $pilotName . " (Evangelion Unit-" . $unitNumber . ")";
}

echo formatPilot("碇シンジ", 1) . "\n";
echo formatPilot("綾波レイ", 0) . "\n";
echo formatPilot("惣流・アスカ・ラングレー", 2) . "\n";

Running the code produces the following output:

php function_basic.php
碇シンジ (Evangelion Unit-1)
綾波レイ (Evangelion Unit-0)
惣流・アスカ・ラングレー (Evangelion Unit-2)
function_default.php
<?php
// Example with a default argument value
// When the sync rate argument is omitted, the default value 0.0 is used

function reportSync(string $pilotName, float $syncRate = 0.0): string {
	if ($syncRate === 0.0) {
		return $pilotName . ": sync rate not measured";
	}
	return $pilotName . ": sync rate " . $syncRate . "%";
}

// Passing the second argument
echo reportSync("碇シンジ", 141.7) . "\n";

// Omitting the second argument (default value 0.0 is used)
echo reportSync("鈴原トウジ") . "\n";

Running the code produces the following output:

php function_default.php
碇シンジ: sync rate 141.7%
鈴原トウジ: sync rate not measured
function_variadic.php
<?php
// Variadic arguments (...) example
// Receives any number of pilot names and displays launch orders

function orderLaunch(string $commander, string ...$pilots): void {
	echo $commander . " issues launch order:\n";
	foreach ($pilots as $pilot) {
		echo "  - " . $pilot . ", launch!\n";
	}
}

// Specifying only one pilot
orderLaunch("葛城ミサト", "碇シンジ");

echo "\n";

// Specifying multiple pilots
orderLaunch("葛城ミサト", "碇シンジ", "綾波レイ", "惣流・アスカ・ラングレー");

Running the code produces the following output:

php function_variadic.php
葛城ミサト issues launch order:
  - 碇シンジ, launch!

葛城ミサト issues launch order:
  - 碇シンジ, launch!
  - 綾波レイ, launch!
  - 惣流・アスカ・ラングレー, launch!
function_strict_types.php
<?php
// Declaring strict_types=1 enables strict type checking
// When types do not match, no implicit conversion occurs and an error is raised
declare(strict_types=1);

function calcDamage(int $baseAttack, float $multiplier): float {
	return $baseAttack * $multiplier;
}

// Called with the correct types
$damage = calcDamage(3000, 1.5);
echo "Damage: " . $damage . "\n"; // outputs 4500

// Without strict_types=1, the string "3000" would be automatically converted to int
// With strict_types=1, this would cause a TypeError
// $damage = calcDamage("3000", 1.5); // TypeError: Argument #1 must be of type int

Running the code produces the following output:

php function_strict_types.php
Damage: 4500
function_recursive.php
<?php
// Recursive function example
// A function that calls itself to perform repetitive calculations
// Uses factorial as an example of staged damage multiplier calculation

function factorial(int $n): int {
	// Termination condition (base case)
	// Without this, the function recurses infinitely
	if ($n <= 1) {
		return 1;
	}
	// Recursive call to repeat the calculation
	return $n * factorial($n - 1);
}

// factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
echo "5! = " . factorial(5) . "\n";
echo "10! = " . factorial(10) . "\n";

// The Fibonacci sequence can also be written recursively
function fibonacci(int $n): int {
	if ($n <= 1) {
		return $n;
	}
	return fibonacci($n - 1) + fibonacci($n - 2);
}

echo "Fibonacci sequence (10th term): " . fibonacci(10) . "\n";

Running the code produces the following output:

php function_recursive.php
5! = 120
10! = 3628800
Fibonacci sequence (10th term): 55

Common Mistakes

Placing a required argument after one with a default value

Defining a required argument (no default value) after an argument that has a default value causes PHP to issue a warning or error. Arguments with default values must always be grouped at the end of the argument list.

ng_func_default.php
<?php
// $unitNumber (no default) comes after $title (has default) — this is wrong
function formatPilot(string $pilotName, string $title = "Pilot", int $unitNumber): string {
	return $pilotName . " (" . $title . " / Unit-" . $unitNumber . ")";
}

echo formatPilot("碇シンジ", "Unit-1 Pilot", 1) . "\n";

Running the code produces the following output:

php ng_func_default.php
Deprecated: Optional parameter $title declared before required parameter $unitNumber in ng_func_default.php on line 3
碇シンジ (Unit-1 Pilot / Unit-1)

Place required arguments first and arguments with default values last.

ok_func_default.php
<?php
// Required arguments first, then arguments with default values
function formatPilot(string $pilotName, int $unitNumber, string $title = "Pilot"): string {
	return $pilotName . " (" . $title . " / Unit-" . $unitNumber . ")";
}

echo formatPilot("碇シンジ", 1) . "\n";
echo formatPilot("綾波レイ", 0, "Unit-0 Pilot") . "\n";

Running the code produces the following output:

php ok_func_default.php
碇シンジ (Pilot / Unit-1)
綾波レイ (Unit-0 Pilot / Unit-0)

Writing a recursive function without a termination condition

A recursive function without a termination condition (base case) calls itself indefinitely, exhausting memory.

ng_func_recursive.php
<?php
// No base case, so this recurses infinitely
function countdown(int $n): void {
	echo $n . "\n";
	countdown($n - 1); // Does not stop when it reaches 0 or below
}

countdown(3);

Running the code produces the following output:

php ng_func_recursive.php
3
2
1
0
-1
...(continues until Fatal error: Maximum function nesting level of '512' reached)

Write a termination condition at the start of the function to stop the recursion.

ok_func_recursive.php
<?php
function countdown(int $n): void {
	// Termination condition: stop recursion when n is 0 or below
	if ($n <= 0) {
		echo "Launch!\n";
		return;
	}
	echo $n . "\n";
	countdown($n - 1);
}

countdown(3);

Running the code produces the following output:

php ok_func_recursive.php
3
2
1
Launch!

Relying on type declarations without strict_types=1

Even with type declarations, without『declare(strict_types=1)』PHP performs implicit type conversion. Passing the string "3000" to an int argument produces no error, and can lead to unexpected calculation results.

ng_func_stricttypes.php
<?php
// Without strict_types=1: a string is silently converted to int
function calcDamage(int $baseAttack, float $multiplier): float {
	return $baseAttack * $multiplier;
}

$damage = calcDamage("3000", 1.5); // A string is accepted without error
echo "Damage: " . $damage . "\n";

Running the code produces the following output:

php ng_func_stricttypes.php
Damage: 4500

Writing declare(strict_types=1) at the top of the file causes a TypeError when types do not match, enabling early bug detection.

ok_func_stricttypes.php
<?php
declare(strict_types=1);

function calcDamage(int $baseAttack, float $multiplier): float {
	return $baseAttack * $multiplier;
}

$damage = calcDamage(3000, 1.5); // Pass the correct type
echo "Damage: " . $damage . "\n";

Running the code produces the following output:

php ok_func_stricttypes.php
Damage: 4500

Summary

To define a function, write the function name, argument list, and processing block after the『function』keyword. Default values can be set for arguments and are used when those arguments are omitted.Arguments with default values must always be placed after arguments without default values.Placing them out of order causes an error.

Writing a type name before an argument name creates a type declaration. Adding『declare(strict_types=1)』at the top of the file enables strict mode, where passing an argument of the wrong type causes an error immediately without implicit conversion.Enabling strict_types allows bugs from unintended type conversions to be caught early.The return type is declared by writing『: type』after the argument list; use『void』for functions that return no value.

Recursive functions call themselves to perform repetitive calculations, and can express mathematical operations such as factorial and Fibonacci sequences concisely. When using recursion, always define a termination condition (base case). Without one, infinite recursion occurs and memory is exhausted. For anonymous functions (closures), see『Closure / Anonymous Functions』. For method definitions in classes, see『class』.

If you find any errors or copyright issues, please .