0Pricing
PHP Academy · Lesson

Defining and Calling Functions

Create your own functions with parameters and return values.

Defining and Calling Functions is a free PHP Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Functions?

Functions let you package reusable logic, giving it a name so you can call it many times without repeating code. Benefits:

  • Avoid repetition (DRY principle)
  • Easier testing and debugging
  • Self-documenting code

Defining a Function

Use the function keyword, a name, optional parameters, and a body:

<?php
function greet(string $name): string {
    return 'Hello, ' . $name . '!';
}

echo greet('Alice'); // Hello, Alice!

Parameters and Arguments

Parameters are the variable names in the definition; arguments are the actual values passed when calling:

<?php
function add(int $a, int $b): int {
    return $a + $b;  // $a and $b are parameters
}

$sum = add(3, 4);  // 3 and 4 are arguments
echo $sum;  // 7

Return Values

Use return to send a value back to the caller. A function without return returns NULL:

<?php
function square(float $n): float {
    return $n * $n;
}

function logMessage(string $msg): void {
    echo '[LOG] ' . $msg . PHP_EOL;
    // void functions must not return a value
}

echo square(4);        // 16
logMessage('started'); // [LOG] started

Passing by Value vs Reference

By default PHP passes arguments by value (a copy). Prefix with & to pass by reference:

<?php
function doubleByValue(int $n): void {
    $n *= 2;  // changes only the local copy
}

function doubleByRef(int &$n): void {
    $n *= 2;  // changes the original
}

$x = 5;
doubleByValue($x);
echo $x; // 5 — unchanged

doubleByRef($x);
echo $x; // 10 — changed

Multiple Return Points

A function can have multiple return statements for early exits:

<?php
function divide(float $a, float $b): ?float {
    if ($b === 0.0) {
        return null;  // early return on error
    }
    return $a / $b;
}

var_dump(divide(10, 0));   // NULL
echo divide(10, 2);         // 5

Function Hoisting

PHP functions are available throughout a file regardless of where they're defined — unlike JavaScript, most PHP functions do NOT need to be declared before use:

<?php
echo double(5);  // 10 — works even though double is defined below

function double(int $n): int {
    return $n * 2;
}

// Exception: functions inside conditionals ARE position-sensitive

Recursive Functions

A function that calls itself is recursive. Always ensure a base case to avoid infinite recursion:

<?php
function factorial(int $n): int {
    if ($n <= 1) return 1;  // base case
    return $n * factorial($n - 1);  // recursive call
}

echo factorial(5);  // 120

Type Declarations

PHP 7+ supports parameter and return type hints. PHP 8 added mixed, never, and intersection types:

<?php
declare(strict_types=1);

function clamp(int $value, int $min, int $max): int {
    return max($min, min($max, $value));
}

echo clamp(150, 0, 100);  // 100
echo clamp(-5,  0, 100);  // 0
echo clamp(42,  0, 100);  // 42

Named Functions vs Built-in

PHP ships with thousands of built-in functions. You can always check if a function exists at runtime:

<?php
if (function_exists('mb_strlen')) {
    echo mb_strlen('こんにちは');  // 5 — correct multi-byte length
} else {
    echo strlen('こんにちは');      // 15 — byte count, wrong for UTF-8
}

Returning Multiple Values

Return multiple values by returning an array and destructuring at the call site:

<?php
function minMax(array $arr): array {
    return [min($arr), max($arr)];
}

[$min, $max] = minMax([3, 1, 7, 2, 9]);
echo "Min: $min, Max: $max";  // Min: 1, Max: 9

Quick Check

What does a PHP function without an explicit return statement return?

Recap: Functions

PHP function essentials:

  • Define with function name(params): returnType
  • Pass by value (default) or by reference with &
  • Functions without return give back NULL
  • Recursion requires a base case
  • Functions are available throughout the file (hoisting)

Next: default and variadic parameters.

Frequently asked questions

Is the “Defining and Calling Functions” lesson free?

Yes — the full text of “Defining and Calling Functions” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Defining and Calling Functions”?

Create your own functions with parameters and return values. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Defining and Calling Functions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining and Calling Functions
  2. Default and Variadic Parameters
  3. Variable Scope: Local and Global
  4. Anonymous Functions and Closures
← Back to PHP Academy