PHP Functions Introduction
In this page:
Defining and Calling Functions
A function packages a block of statements under a name so you can run that same logic repeatedly without retyping it. PHP parses the definition when the file loads, but the code inside only actually runs at the moment something calls the function by name.
Example: Defining and Calling Functions
<?php
function greet() {
echo "Hello!";
}
greet();
?>
Login to try C/C++/Java/PHP code in the editor
Function Naming Rules
Function names must start with a letter or an underscore, and while PHP itself doesn't care about the casing you use, staying consistent — camelCase or snake_case throughout a project — makes a codebase far easier to scan and predict.
Example: Function Naming Rules
<?php
function calculateTotal() {
return 100;
}
echo calculateTotal();
?>
Login to try C/C++/Java/PHP code in the editor
Variable Scope inside Functions
Any variable created inside a function only exists for that function's own execution and disappears once it returns — code outside can't see it. To read or modify a variable from the surrounding global scope inside a function, you have to explicitly declare it with the global keyword first.
Example: Variable Scope inside Functions
<?php
$count = 10;
function showCount() {
global $count;
echo $count;
}
showCount();
?>
Login to try C/C++/Java/PHP code in the editor
Functions with No Arguments
A function doesn't need parameters to be useful — plenty of functions just perform a fixed task or print a fixed message each time they're called, with nothing external needed to do their job.
Example: Functions with No Arguments
<?php
function printWelcome() {
echo "Welcome to the site!";
}
printWelcome();
?>
Login to try C/C++/Java/PHP code in the editor
Conditional Function Declarations
Defining a function inside an if block means the function only comes into existence if that block actually executes — PHP registers it conditionally, at runtime, rather than immediately when the file is parsed the way an unconditional function definition would be.
Example: Conditional Function Declarations
<?php
$defineIt = true;
if ($defineIt) {
function sayHi() {
echo "Hi!";
}
}
sayHi();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: