SyntaxStudy
Sign Up
PHP Beginner 1 min read

Functions in PHP

PHP Functions

Functions are reusable blocks of code defined with function.

Type Declarations (PHP 7+)

Declare parameter and return types for safer code.

Return Types

Add : type after the parentheses. Use ?type for nullable.

Example
<?php
// Basic function
function greet(string $name): string {
    return "Hello, $name!";
}
echo greet("Alice");  // Hello, Alice!

// Default parameters
function power(float $base, int $exp = 2): float {
    return $base ** $exp;
}
echo power(3);     // 9
echo power(2, 10); // 1024

// Multiple return types (PHP 8 union types)
function divide(int $a, int $b): float|false {
    return $b !== 0 ? $a / $b : false;
}
?>