Defining functions
Learn to define functions with the function keyword.
Defining functions
A function is a block of code that performs a task and can be run whenever you want. In PHP a function starts with the function keyword, followed by a name, parentheses and a body in curly braces.
Example: function greet() { echo "Hello"; }. Here greet is the function name; the parentheses are empty for now and the body uses echo to print a message. Defining a function does not run it; it waits to be called.
Function body and naming
Function names must start with a letter or underscore; they cannot start with a digit. PHP is case-sensitive, so greet and Greet are different functions.
The body is the block of code between curly braces. It can contain echo, variable assignments and other statements. Names like printHeader or getUser that describe an action are a good habit.
Exercise Print a welcome message
Define a parameterless function named printWelcome. In the body, write echo "Welcome!" . "\n";. Then call the function once.
Show example solution
Define with function printWelcome() { ... }, put echo "Welcome!" . "\n"; in the body, then call with printWelcome();.
Example solution:
<?php
// Define printWelcome and call it
function printWelcome() {
echo "Welcome!" . "\n";
}
printWelcome();
Test yourself
-
Which is a valid function definition?
- greet() { echo "Hi"; }
- function greet() { echo "Hi"; }
- func greet() { echo "Hi"; }
- function greet[] { echo "Hi"; }
Show answer
function greet() { echo "Hi"; } — Correct. The function keyword, name, parentheses and braces are required.
-
Complete the function name
function ____() { echo "Merhaba"; }Show answer
function greet() { echo "Merhaba"; } -
Match the parts of a function
- function
- Keyword
- greet
- Function name
- { echo "Hi"; }
- Body