Kodokon kodokon.com

Functions: declare, type, return

Create your own functions with typed parameters, default values, and return values.

8 min · 3 questions

Open this lesson in Kodokon

A function is a block of instructions you give a name to, so you can reuse it as many times as needed with a simple call. Write once, use everywhere: that's the principle. You declare it with the function keyword, followed by the name, parentheses, and a block inside braces. The : void marking after the parentheses says the function returns nothing: it simply acts.

PHP
<?php

function sayHello(): void
{
    echo "Hello and welcome!<br>";
}

sayHello();
sayHello();
One declaration, two calls, two outputs.

The parentheses hold the parameters: variables the function receives on each call. The concrete value supplied when calling is called an argument. In modern PHP, you type each parameter (float $price) and the returned value (: float after the parentheses): PHP then refuses values of the wrong type, which prevents many bugs. The return statement sends a result back to the call site and immediately stops the function.

PHP
<?php

function addTax(float $price): float
{
    return $price * 1.2;
}

echo addTax(100);
echo "<br>";
echo addTax(50);
Displays 120 then 60: the result goes back to the caller.

A parameter can receive a default value with =: if the call doesn't provide an argument for that parameter, the default value takes over. Golden rule: parameters with defaults go after the required ones.

PHP
<?php

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

echo greet("Awa");
echo "<br>";
echo greet("Awa", "Good evening");
Without a second argument, greeting is “Hello”.
PHP
<?php

function totalPrice(
    float $unitPrice,
    int $quantity = 1
): float {
    return $unitPrice * $quantity;
}

echo totalPrice(19.9, 3);
echo "<br>";
echo totalPrice(8.5);
Recap: types, default, and return all together.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which keyword declares a function in PHP?
    • def
    • function
    • func
  2. What does the return statement do?
    • It prints a value to the screen
    • It returns a value and stops the function
    • It restarts the function from the beginning
  3. With function greet(string $name, string $greeting = "Hello"), what is $greeting if you call greet("Awa")?
    • An empty string
    • null
    • The default value “Hello”