Topics Control Flow & Functions Functions & Variable Scope
beginner 15 min read

Functions & Variable Scope

Defining functions, parameters, return types, type declarations, and scope.

Defining Functions

function greet(string \$name): string {
return "Hello, \$name!";
}

Parameters

// Default values
function setSize(int \$size = 10): void { ... }

// Named arguments (PHP 8.0+)
setSize(size: 20);

// Variadic
function sum(int ...\$numbers): int {
return array_sum(\$numbers);
}

// Strict types
declare(strict_types=1);

Return Types

: void
: ?int
: int|string // union types (PHP 8.0+)
: mixed
: never // (PHP 8.1+)

Variable Scope

Use global to access global variables, or pass them as parameters. Static variables persist between calls.

Examples

<?php
function add(int $a, int $b): int {
    return $a + $b;
}
echo add(5, 3);
echo add(b: 10, a: 7);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.