Declaring and calling functions
A function is a named block of code you can call with inputs (parameters) and get a result back with return. A function without return gives back null. Top-level functions are available anywhere in the file, even above their definition, because PHP compiles the whole file before running it. Function names are case-insensitive, but always call them exactly as declared (camelCase is the PSR convention).
<?php
echo greet("Asha"), "\n"; // works: defined further down
function greet(string $name): string
{
return "Hello, $name!";
}
function logLine(string $msg): void
{
echo "[log] $msg\n"; // void: returns nothing
}
logLine("started");
var_dump(logLine("again")); // a void call evaluates to null
// variables inside a function are local
$count = 10;
function tryToChange(): void
{
$count = 99; // a new local variable
echo "inside: $count\n";
}
tryToChange();
echo "outside: $count\n";Hello, Asha!
[log] started
[log] again
NULL
inside: 99
outside: 10Unlike JavaScript, a PHP function cannot see variables from outside it. Pass what it needs as parameters. (The global keyword exists; modern code avoids it.)
Write function square(int $n): int and print square(7).
ArgumentCountError: Too few arguments
<?php
function greet(string $name, string $greeting): string
{
return "$greeting, $name!";
}
echo greet("Asha");Fatal error: Uncaught ArgumentCountError: Too few arguments to function greet(), 1 passed in main.php on line 7 and exactly 2 expected in main.php:2
Stack trace:
#0 main.php(7): greet('Asha')
#1 {main}
thrown in main.php on line 2Every parameter without a default is required. The message tells you both sides: the call on line 7 passed 1 argument, the function on line 2 expects exactly 2. (Passing too many arguments to a user function is silently allowed — the extras are ignored.)
Pass the missing argument, or give the parameter a default value if most callers use the same one.
<?php
function greet(string $name, string $greeting = "Hello"): string
{
return "$greeting, $name!";
}
echo greet("Asha");