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%

1. Functions & Variable Scope

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

Functions in PHP: Definitions, Scope & Usage

Study Deep: Variable Visibility Hierarchy

In PHP, variable visibility is strictly managed to prevent accidental data corruption across the application.

  1. Local (Lowest): The variable exists only for the duration of the function call.
  2. Global (Middle): The variable persists throughout the script execution but requires explicit access (global) from within functions.
  3. Superglobal (Highest): These ($_POST, $_GET, etc.) are pre-defined by PHP and are accessible from any scope without any special declaration.

BCA Examination Tip: When asked to explain function scope, always include the static keyword. It is a favorite exam topic because it breaks the "local variables are destroyed" rule.

1. What is a Function?

A Function is a named, self-contained block of code that performs a specific, well-defined task. Once defined, a function can be called any number of times from anywhere in a script.

Why Use Functions?

  • Modularity: Break large programs into smaller, manageable, single-purpose pieces.
  • Reusability: Write code once, use it many times — no repeated logic.
  • Abstraction: Callers only need to know what a function does, not how.
  • Easier Debugging: Isolated blocks are far easier to test and fix.
  • Readability: Well-named functions make code read like plain English.

2. Key Terminology

TermDefinitionExample
Function DefinitionBlock of code that gives the function its name, parameters, and bodyfunction greet($name) { ... }
Function CallStatement that executes / invokes the functiongreet("Rohit");
ParameterA variable placeholder in the function definition$name in function greet($name)
ArgumentThe actual value passed when calling the function"Rohit" in greet("Rohit")
Return ValueValue the function sends back using returnreturn $sum;

3. Defining and Calling Functions

Syntax:

function functionName($param1, $param2) {
  // Code to execute
  return $result;
}
functionName(value1, value2);

Example 1 — No parameters, no return:

function showWelcome() {
  echo "Welcome to Web Based Programming!";
}
showWelcome(); // Output: Welcome to Web Based Programming!

Example 2 — With parameters and return value:

function add($a, $b) {
  return $a + $b;
}
echo add(5, 10); // Output: 15

Example 3 — Default parameter values: If no argument is provided, the default value is used automatically.

function greet($name = "Guest") {
  echo "Hello, $name!";
}
greet("Rohit"); // Hello, Rohit!
greet();        // Hello, Guest!

Example 4 — PHP 7+ Type Declarations (Type Hints): You can enforce parameter and return types for safer code.

function multiply(int $a, int $b): int {
  return $a * $b;
}
echo multiply(4, 5); // Output: 20

4. Variable Scope

Scope defines the region of a script in which a particular variable can be accessed. Scope errors are a very common source of bugs in PHP.

a) Local Scope A variable declared inside a function is LOCAL. It is created when the function starts and destroyed when it ends.

function myTest() {
  $x = 5; // Only visible inside myTest()
  echo "Inside: $x";
}
myTest();
echo $x; // FATAL ERROR: undefined variable

b) Global Scope A variable declared outside all functions is GLOBAL. PHP does not automatically expose global variables inside functions — you must use the global keyword.

$siteName = "SikshaSarovar";

function showSite() {
  global $siteName; // Explicitly request access
  echo "Welcome to $siteName!";
}
showSite(); // Welcome to SikshaSarovar!

Alternative: Use the $GLOBALS superglobal:

echo $GLOBALS['siteName'];

c) Static Scope A static variable retains its value between calls. It is initialized only ONCE on the very first call. Use case: Counters, accumulators, caching expensive calculations.

function visitCount() {
  static $count = 0; // Initialized only on first call
  $count++;
  echo "Visited: $count time(s)<br>";
}
visitCount(); // Visited: 1 time(s)
visitCount(); // Visited: 2 time(s)
visitCount(); // Visited: 3 time(s)

5. Comparison of Variable Scopes

FeatureLocalGlobalStatic
Declared LocationInside a functionOutside all functionsInside a function (with static)
Accessible FromOnly inside its own functionAnywhere (needs global keyword inside functions)Only inside its own function
LifetimeUntil function execution endsUntil entire script endsUntil entire script ends
MemoryFreed after function callPersists throughout scriptPersists throughout script
Best Use CaseTemporary calculationsShared config / constantsCounters, memoization