Learn/PHP/6. Functions
Lesson 6 of 15
Sign in

PHP, lesson 6

Functions

A function packages a piece of code under a name, so you can run it whenever you need it, give it different inputs, and get a result back. Functions keep programs short, and a well-named function explains what a block of code is for.

Defining and calling

$name is a parameter; "Mia" is the argument passed in the call. string before the parameter and : void after the parentheses are type declarations: this function takes a string and returns nothing. Types are optional in PHP, but modern code uses them everywhere because they catch mistakes early and document the function for free.

Returning values

return sends a value back to the caller and ends the function:

A function that just prints its result can't be reused in a calculation. Prefer returning values and let the caller decide what to do with them.

2 exercises to try what you just read.

Exercise 1

Weather converter

Press Ctrl Enter or Check to test your code.

Exercise 2

Price tags

Press Ctrl Enter or Check to test your code.

Common return types are int, float, string, bool, array, void (nothing) and nullable types such as ?int (an int or null). A union like int|string allows either.

Default values and named arguments

Parameters can have defaults, which are used when the caller leaves them out. Since PHP 8 you can also pass arguments by name, which makes calls readable and lets you skip optional parameters:

Strict types

By default PHP converts arguments to the declared type when it can, so passing "5" to an int parameter quietly becomes 5. Put this line right after <?php to switch that off for the file:

Now passing the wrong type throws a TypeError instead of guessing. Many projects use strict types in every file. (Passing an int where a float is expected is still allowed.)

Scope

Variables inside a function are local: they exist only during that call. Unlike many languages, PHP functions also can't see variables from outside, not even to read them:

There is a global keyword to reach outside, but passing values in as arguments is far clearer and easier to test. A static variable inside a function keeps its value between calls, which is occasionally useful for counters and caches.

Arrow functions, briefly

For tiny functions PHP has a short form, fn ($x) => $x * 2, which you can store in a variable or pass to other functions. Unlike normal functions, arrow functions can read variables from the surrounding code. They'll be important in lesson 14.

Further reading

  • User-defined functions
  • Function arguments
  • Returning values
  • Type declarations
  • Variable scope

Finish toFahrenheit() so it returns the temperature in °F using F = C × 9 / 5 + 32. The rest of the program reads one Celsius value per line until the input ends and prints each result with one decimal.

Sample input:

Sample output:

Write priceTag(float $price, int $discount = 0): string. With no discount it returns the price with two decimals, like 19.99. With a discount (a percentage) it returns the reduced price followed by the discount in brackets, like 15.99 (20% off).

Each input line holds a price, optionally followed by a discount. The starter calls your function for each line.

Sample input:

Sample output:

<?php

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

greet("Mia");
greet("Sam");
<?php

function area(float $width, float $height): float
{
    return $width * $height;
}

$room = area(4, 3) + area(2, 2);
echo $room, "\n";   // 16
<?php

function priceWithTax(float $amount, float $rate = 0.2, bool $round = true): float
{
    $total = $amount * (1 + $rate);
    return $round ? round($total, 2) : $total;
}

echo priceWithTax(10), "\n";                // rate 0.2
echo priceWithTax(10, 0.05), "\n";          // positional
echo priceWithTax(10, round: false), "\n";  // named: skip $rate
<?php

declare(strict_types=1);
<?php

$bonus = 10;

function addBonus(int $score): int
{
    // $bonus is undefined here
    return $score + 10;
}
0
100
-40
32.0
212.0
-40.0
19.99
19.99 20
5 50
19.99
15.99 (20% off)
2.50 (50% off)