Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 8: User Defined Functions

Lesson 15 of 35 in the free Web Based Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

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): string constrains both the parameter and the return value. In default (coercive) mode PHP converts compatible scalars; under declare(strict_types=1) a mismatch throws TypeError.
  • Return values: return immediately ends the function and hands a value to the caller. A function with no return yields null. echo inside a function prints; return delivers — 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's use clause.
  • 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

  1. Start Apache from the XAMPP Control Panel.
  2. Save the snippet as p08_functions.php in C:\xampp\htdocs\wbplab.
  3. Run http://localhost/wbplab/p08_functions.php or php p08_functions.php.
  4. Call calculateArea("5.5", "3") with string arguments and observe coercive mode converting them; then add declare(strict_types=1); at the top and re-run to see the TypeError.
  5. 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): string concatenates a greeting with the . operator and returns it; the caller echoes the result — the function itself prints nothing.
  • calculateArea(float $length, float $width): float returns the product $length * $width; with arguments 5.5 and 3.0 that is 16.5.
  • factorial(int $n): int is recursive. The guard if ($n <= 1) return 1; is the base case (it also protects against 0 and negative inputs). Otherwise it returns $n factorial($n - 1), so factorial(5) expands to 5 4 3 2 * 1.
  • The three echo statements at the bottom invoke each function and append \n for 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

  1. Difference between echo inside a function and return? echo prints immediately as a side effect; return hands the value back so the caller can print, store or reuse it.
  2. What does a PHP function return if it has no return statement? null.
  3. What two parts must every recursive function have? A base case that terminates recursion and a recursive step that converges toward it.
  4. What happens without the $n <= 1 base case? Infinite recursion — each call adds a stack frame until PHP aborts with a fatal error.
  5. How does strict_types change the typed signatures here? Scalar arguments are no longer coerced; passing "5.5" to a float parameter throws TypeError instead of converting.
  6. Are PHP function names case-sensitive? No — greetUser() and GREETUSER() call the same function (variables, in contrast, are case-sensitive).

CO Mapping

CO1, CO2