Aim
To show the application of user-defined functions in PHP — including typed parameters, return values and recursion — through three practical examples.
Theory
A user-defined function is a named, reusable block declared with the function keyword. Functions are the primary unit of abstraction: they let you name an operation once and invoke it many times, which eliminates duplication (DRY) and makes each piece independently testable.
Points the snippet exercises:
- Type declarations:
function greetUser(string $name): stringconstrains both the parameter and the return value. In default (coercive) mode PHP converts compatible scalars; underdeclare(strict_types=1)a mismatch throwsTypeError. - Return values:
returnimmediately ends the function and hands a value to the caller. A function with noreturnyieldsnull.echoinside a function prints;returndelivers — the caller decides what to do with a returned value, which is why returning is the cleaner design. - Recursion: a function that calls itself, as
factorial()does. Every recursive function needs a base case (if ($n <= 1) return 1;) that stops the descent, and a recursive step that moves toward it ($n * factorial($n - 1)). Each pending call occupies a stack frame, so unbounded recursion exhausts memory. - Scope: variables inside a function are local. Outer variables are invisible unless passed as arguments (preferred), imported with
global, or captured by a closure'suseclause. - Parameters may take default values (
function f($x = 10)), be passed by reference (&$x), or be variadic (...$nums).
Requirements
- XAMPP/WAMP with PHP 8.x, or PHP CLI
- Code editor (VS Code); browser or terminal
Procedure
- Start Apache from the XAMPP Control Panel.
- Save the snippet as
p08_functions.phpinC:\xampp\htdocs\wbplab. - Run
http://localhost/wbplab/p08_functions.phporphp p08_functions.php. - Call
calculateArea("5.5", "3")with string arguments and observe coercive mode converting them; then adddeclare(strict_types=1);at the top and re-run to see theTypeError. - Trace
factorial(5)on paper — write out the five stacked calls down to the base case and the multiplications on the way back up.
Explanation of the Code
greetUser(string $name): stringconcatenates a greeting with the.operator and returns it; the callerechoes the result — the function itself prints nothing.calculateArea(float $length, float $width): floatreturns the product$length * $width; with arguments5.5and3.0that is16.5.factorial(int $n): intis recursive. The guardif ($n <= 1) return 1;is the base case (it also protects against 0 and negative inputs). Otherwise it returns$n factorial($n - 1), sofactorial(5)expands to5 4 3 2 * 1.- The three
echostatements at the bottom invoke each function and append\nfor line breaks.
Expected Output
Hello, Riya
Rectangle area: 16.5
Factorial of 5: 120
Three lines: the greeting, the area 16.5, and 120 computed by five nested recursive calls.
🎯 Viva Questions
- Difference between
echoinside a function andreturn?echoprints immediately as a side effect;returnhands the value back so the caller can print, store or reuse it. - What does a PHP function return if it has no
returnstatement?null. - What two parts must every recursive function have? A base case that terminates recursion and a recursive step that converges toward it.
- What happens without the
$n <= 1base case? Infinite recursion — each call adds a stack frame until PHP aborts with a fatal error. - How does
strict_typeschange the typed signatures here? Scalar arguments are no longer coerced; passing"5.5"to afloatparameter throwsTypeErrorinstead of converting. - Are PHP function names case-sensitive? No —
greetUser()andGREETUSER()call the same function (variables, in contrast, are case-sensitive).
CO Mapping
CO1, CO2