← Back to PHP Course | Chapter 5: Functions | Lesson 1 of 10

PHP Functions Introduction

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
<?php
function greet() {
    echo "Hello!";
}
greet();
?>

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
<?php
function calculateTotal() {
    return 100;
}
echo calculateTotal();
?>

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
<?php
$count = 10;

function showCount() {
    global $count;
    echo $count;
}
showCount();
?>

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
<?php
function printWelcome() {
    echo "Welcome to the site!";
}
printWelcome();
?>

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
<?php
$defineIt = true;
if ($defineIt) {
    function sayHi() {
        echo "Hi!";
    }
}
sayHi();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.