A function gets more useful when you can give it data to work with. The values it accepts are called parameters.
<?php
function greet(string $name): void
{
echo "Hello, $name!\n";
}
greet("Asha");
greet("Ben");
Hello, Asha!
Hello, Ben!
Parameter vs argument
These two words are easy to mix up.
- A parameter is the variable in the function definition:
$name. - An argument is the value you pass when you call it:
"Asha".
Think of a parameter as an empty seat and an argument as the person who sits in it.
More than one parameter
Separate them with commas. Arguments are matched by position.
<?php
function introduce(string $name, int $age, string $city): void
{
echo "$name is $age years old and lives in $city.\n";
}
introduce("Ravi", 28, "Delhi");
Ravi is 28 years old and lives in Delhi.
If you swap the order, you swap the meaning: introduce(28, "Ravi", ...) would be wrong. PHP can help you catch it with types, and Named Arguments make it even safer.
Too few arguments
If you forget a required argument, PHP throws an error.
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
try {
echo add(5);
} catch (ArgumentCountError $e) {
echo $e->getMessage();
}
Too few arguments to function add(), 1 passed in /path/to/index.php on line 8 and exactly 2 expected
Too many arguments
Extra arguments to your own function are ignored, with no error.
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
echo add(1, 2, 3);
3
Arguments can be any expression
<?php
function double(int $n): int
{
return $n * 2;
}
$base = 4;
echo double($base) . "\n";
echo double($base + 1) . "\n";
echo double(double(3));
8
10
12
Arrays and other types
A parameter can hold any type, including an array.
<?php
function listItems(array $items): void
{
foreach ($items as $item) {
echo "- $item\n";
}
}
listItems(["tea", "coffee"]);
- tea
- coffee