WikiGalaxy

Personalize

PHP Functions: Understanding Basics

Defining a Function:

In PHP, functions are defined using the function keyword followed by the function name and parentheses. The code block within curly braces is the function body.


function sayHello() {
    echo "Hello, World!";
}
sayHello();
    

Console Output:

Hello, World!

PHP Functions: Parameters and Arguments

Using Parameters:

Functions can take parameters, which are variables passed to the function. These are specified within the parentheses of the function definition.


function greet($name) {
    echo "Hello, $name!";
}
greet("Alice");
    

Console Output:

Hello, Alice!

PHP Functions: Return Values

Returning Values:

Functions can return values using the return statement. This allows the function to send data back to the calling code.


function add($a, $b) {
    return $a + $b;
}
$result = add(5, 3);
echo $result;
    

Console Output:

8

PHP Functions: Default Parameters

Default Parameter Values:

PHP allows you to set default values for function parameters. If no argument is provided, the default value will be used.


function greet($name = "Guest") {
    echo "Hello, $name!";
}
greet();
    

Console Output:

Hello, Guest!

PHP Functions: Variable Scope

Understanding Scope:

Variables declared inside a function are local to that function and cannot be accessed outside. Global variables can be accessed using the global keyword.


$globalVar = "I am global";
function testScope() {
    global $globalVar;
    echo $globalVar;
}
testScope();
    

Console Output:

I am global

PHP Functions: Anonymous Functions

Anonymous Functions:

Anonymous functions, also known as closures, can be assigned to variables and passed as arguments to other functions.


$greet = function($name) {
    echo "Hello, $name!";
};
$greet("Bob");
    

Console Output:

Hello, Bob!

PHP Functions: Recursive Functions

Recursive Functions:

A recursive function is a function that calls itself in order to solve a problem. It's commonly used for tasks that can be divided into similar subtasks.


function factorial($n) {
    if ($n == 0) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}
echo factorial(5);
    

Console Output:

120

PHP Functions: Type Declarations

Type Declarations:

PHP 7 introduced type declarations, allowing you to specify the expected data types for function arguments and return values.


function sum(int $a, int $b): int {
    return $a + $b;
}
echo sum(2, 3);
    

Console Output:

5

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025