Lessons → PHP Basics → Lesson 6

Functions

PHP
⏱ 15 min read📖 BeginnerNot completed

Functions are reusable blocks of code. Instead of writing the same code multiple times, you define a function once and call it whenever needed.

Defining a Function

PHP
<?php
function greet() {
    echo "Hello, World!";
}
greet();  // Hello, World!
?>

Functions with Parameters

PHP
<?php
function greet($name) {
    echo "Hello, $name!";
}
greet("Suraj");  // Hello, Suraj!
greet("John");   // Hello, John!
?>

Default Parameters

PHP
<?php
function greet($name = "World") {
    echo "Hello, $name!";
}
greet();         // Hello, World!
greet("Suraj");  // Hello, Suraj!
?>

Return Values

PHP
<?php
function add($a, $b) {
    return $a + $b;
}
$result = add(5, 3);
echo $result;  // 8

function getFullName($first, $last) {
    return "$first $last";
}
echo getFullName("John", "Doe");  // John Doe
?>

Type Declarations (PHP 7+)

PHP
<?php
function add(int $a, int $b): int {
    return $a + $b;
}
echo add(5, 3);   // 8
echo add(5.5, 3); // 8 — float gets converted to int

function getUserName(int $id): string {
    return "User_$id";
}
?>

Arrow Functions (PHP 7.4+)

PHP
<?php
// Traditional
$double = function($n) { return $n * 2; };

// Arrow function (shorter)
$double = fn($n) => $n * 2;
echo $double(5);  // 10

// Very useful with array functions
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10]
?>

Variable Scope

PHP
<?php
$message = "Hello";  // Global variable

function test() {
    // Can't access $message here without 'global'
    echo $message;  // Error!
}

function test2() {
    global $message;  // Import global variable
    echo $message;    // Hello
}
test2();
?>
💡
In Laravel, you'll rarely use global. Instead, pass data through function parameters or use dependency injection — much cleaner!
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take the PHP Basics quiz.

Take Quiz →