A function is a named block of code that you can run whenever you want. You write it once and call it as many times as you need.
Think of a function as a recipe. You write the recipe once. Every time you want the dish, you follow the recipe instead of writing the steps again.
<?php
function sayHello(): void
{
echo "Hello, welcome to PHP!\n";
}
sayHello();
sayHello();
Hello, welcome to PHP!
Hello, welcome to PHP!
The parts of a function
function name(): returnType
{
// the code
}
functionis the keyword that starts it.sayHellois the name. Follow the same rules as variable names, without the$.()holds the parameters (empty here).: voidsays the function returns nothing. Return types come soon.{ ... }holds the code.
Writing the function does not run it. It runs only when you call it by name followed by brackets.
Why use functions
- No repetition. Write the code once, use it everywhere.
- One place to fix. If the logic changes, you change it in one spot.
- Readable code.
calculateTax()says more than ten lines of maths. - Easy testing. A small function is easy to check on its own.
A function can call another function
<?php
function printLine(): void
{
echo str_repeat("-", 20) . "\n";
}
function printHeader(): void
{
printLine();
echo "MY SHOP\n";
printLine();
}
printHeader();
--------------------
MY SHOP
--------------------
Where to define functions
In PHP you can call a function before the line where it is defined, as long as it is defined at the top level of the file (not inside an if).
<?php
echo greet(); // works, even though greet() is defined below
function greet(): string
{
return "Hi!";
}
Hi!
Naming
Name functions with a verb: getUser(), calculateTotal(), isValidEmail(). Use camelCase. A good name tells you what the function does without reading it.
Built-in functions
strlen() and count(). You have been calling them all along. Your own functions work the same way.Exercise: a footer function
Write a function printFooter() that prints Copyright 2026. Call it twice.
Show a possible solution
<?php
function printFooter(): void
{
echo "Copyright 2026\n";
}
printFooter();
printFooter();
Copyright 2026
Copyright 2026