Skip to content

Chapter 9 of 38

Functions

Design parameters, returns, types, variadics, named arguments, callbacks, and recursion.

40 minutes 10 quick checksBy Subha Prasad
Lesson 9 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Functions have local scope, defaults, variadic parameters, named arguments, callbacks, and declared parameter/return types. Values use copy-on-write; reference parameters should be rare and explicit.

Practical example

<?php
declare(strict_types=1);
function total(float ...$values): float { return array_sum($values); }
function factorial(int $n): int { if ($n < 0) throw new InvalidArgumentException(); return $n <= 1 ? 1 : $n * factorial($n - 1); }

Named arguments make parameter names part of the public API. Closures capture through use; arrow functions capture by value automatically. Recursion requires a base case and can exhaust resources. Keep side effects and failure contracts visible.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes function declaration?
Which PHP term matches this description: A named reusable callable with parameters and a body.
Which statement best describes return type?
Which PHP term matches this description: A declaration constraining a function's returned value.
Which statement best describes variadic parameter?
Which PHP term matches this description: A ... parameter collecting remaining arguments.
Which statement best describes named argument?
Which PHP term matches this description: A call argument associated by parameter name.
Which statement best describes recursion?
Which PHP term matches this description: A function calling itself toward a base case.

0 of 10 checks passed

Your progress is saved on this device.

Functions | PHP Lesson | Subha Prasad