PHP Basics · Beginner Level · Chapter 10

PHP Functions क्या है?
Complete Guide in Hindi

PHP Functions की पूरी जानकारी — Function define करना, Parameters, Return Values, Default Values, Type Hints, Variadic Functions, Anonymous Functions, और Arrow Functions।

📦 Function Define 🔢 Parameters ↩️ Return Values 🎯 Default Values ➡️ Arrow Functions
functionkeyword से define
returnValue वापस भेजना
...Variadic — unlimited params
fn()Arrow function PHP 7.4+

📋 इस Article में क्या-क्या है

  1. Function क्या है?
  2. Function Define करना
  3. Parameters और Arguments
  4. Return Values
  5. Default Parameter Values
  6. Type Hints (PHP 7+)
  7. Variadic Functions (...)
  8. Variable Functions
  9. Anonymous Functions
  10. Arrow Functions (PHP 7.4+)
1
Function क्या है?

Function एक reusable code block है जो एक specific task करता है। एक बार define करो, बार-बार call करो। Code duplication खत्म, errors कम, maintenance आसान।

PHP में 1000+ built-in functions हैं — strlen(), array_map(), json_encode() — यह सब functions हैं। हम खुद भी user-defined functions बना सकते हैं।
Function = एक काम को pack करना। जैसे calculator का + button — हर बार addition का logic लिखने की ज़रूरत नहीं।

❌ बिना Function — Repetitive Code

// हर बार same code!
$area1 = 5 * 3;
$area2 = 8 * 4;
$area3 = 10 * 6;

✅ Function से — DRY Code

function area($l, $w) { return $l * $w; }
area(5, 3);
area(8, 4);
area(10, 6);

2
Function Define और Call करना
def
ine

function keyword

function keyword से define करो, फिर कहीं से भी call करो। PHP में functions case-insensitive हैं और hoisted होती हैं — define करने से पहले भी call कर सकते हो।

Reusable Case-insensitive Hoisted
function functionName( $param1, $param2 ) {
  // function body
  return $result; // optional
}

// Call करना:
functionName( $arg1, $arg2 );
FUNCTION — BASIC EXAMPLES
<?php
// 1. No params, no return
function greet() {
  echo "नमस्ते! HindiNotesPoint में आपका स्वागत है।";
}
greet(); // Call करो

// 2. Parameters के साथ
function namasteKaro($naam) {
  echo "नमस्ते, $naam!";
}
namasteKaro("Rahul"); // नमस्ते, Rahul!
namasteKaro("Priya"); // नमस्ते, Priya!

// 3. Define से पहले call — PHP में allowed!
sayHello(); // ✅ Works!
function sayHello() { echo "Hello!"; }
?>
Naming Rules: Function names letter या underscore से शुरू होती हैं, numbers से नहीं। camelCase (myFunction) या snake_case (my_function) — दोनों common हैं। PHP built-in functions mostly snake_case में हैं।

3
Parameters और Arguments
Parameters — function definition में variables। Arguments — function call में actual values। दोनों often interchangeably use होते हैं।
PARAMETERS — Pass by Value vs Pass by Reference
<?php
// Pass by Value — original नहीं बदलता
function double($num) {
  $num = $num * 2;
  echo $num;
}
$x = 5;
double($x); // 10
echo $x; // 5 — original unchanged!

// Pass by Reference — & से original बदलता है
function doubleRef(&$num) {
  $num = $num * 2;
}
$y = 5;
doubleRef($y);
echo $y; // 10 — original changed!

// Multiple parameters
function add($a, $b, $c) {
  return $a + $b + $c;
}
echo add(10, 20, 30); // 60
?>

4
Return Values — Value वापस भेजना
ret
urn

return statement

Function से value वापस caller को भेजता है। return के बाद function तुरंत बंद होती है — बाकी code execute नहीं होता। Multiple values return करने के लिए array use करो।

Single value Array से multiple Early exit
RETURN — EXAMPLES
<?php
// Basic return
function square($n) {
  return $n ** 2;
}
$result = square(5);
echo $result; // 25

// Return से early exit
function divide($a, $b) {
  if ($b === 0) {
    return "❌ Zero से divide नहीं कर सकते";
  } // बाकी code यहाँ नहीं पहुँचेगा
  return $a / $b;
}
echo divide(10, 2); // 5
echo divide(10, 0); // ❌ Zero से divide नहीं कर सकते

// Multiple values — array में return
function minMax($arr) {
  return ["min" => min($arr), "max" => max($arr)];
}
["min" => $min, "max" => $max] = minMax([5, 2, 8, 1]);
echo "Min: $min, Max: $max"; // Min: 1, Max: 8
?>

5
Default Parameter Values — Optional Parameters
Parameters को default values दे सकते हो। Call करते समय वो argument न दो तो default use होगी। Default parameters हमेशा right side में होने चाहिए।
DEFAULT PARAMETERS — EXAMPLES
<?php
// Default value
function greet($naam, $greeting = "नमस्ते") {
  echo "$greeting, $naam!";
}
greet("Rahul"); // नमस्ते, Rahul!
greet("Priya", "Hello"); // Hello, Priya!

// Multiple defaults
function createUser($naam, $role = "user", $active = true) {
  return compact("naam", "role", "active");
}
print_r(createUser("Rahul"));
// [naam=>Rahul, role=>user, active=>true]
print_r(createUser("Admin", "admin"));
// [naam=>Admin, role=>admin, active=>true]

// Named arguments (PHP 8) — order free!
greet(greeting: "Hello", naam: "Amit");
// Hello, Amit! — order matter नहीं
?>
⚠️ Rule: Default parameters हमेशा right side में रखो। function f($a = 1, $b) ❌ Error। function f($a, $b = 1) ✅ Correct।

6
Type Hints — Data Types Enforce करना
PHP 7+ में Type Hints से function parameters और return values के types enforce कर सकते हो। Bugs कम होते हैं, code readable होता है।
TYPE HINTS — PHP 7+ & PHP 8
<?php
declare(strict_types=1); // Strict mode on

// Parameters + Return type hints
function add(int $a, int $b): int {
  return $a + $b;
}
echo add(5, 10); // 15
// add("5", 10) → TypeError with strict_types=1

// Nullable type — null allowed
function findUser(int $id): ?array {
  // null return allowed
  return $id === 1 ? ["naam" => "Rahul"] : null;
}

// Union types (PHP 8)
function format(int|float $num): string {
  return number_format($num, 2);
}
echo format(1234); // 1,234.00
echo format(99.5); // 99.50

// void — कुछ return नहीं
function logMessage(string $msg): void {
  echo "[LOG] $msg";
  // return कुछ नहीं
}
?>
Type HintAcceptsPHP Version
intInteger numbersPHP 7+
floatDecimal numbersPHP 7+
stringTextPHP 7+
booltrue/falsePHP 7+
arrayArraysPHP 7+
?intint या nullPHP 7.1+
int|floatUnion typesPHP 8+
mixedAny typePHP 8+
voidReturn type — कुछ नहींPHP 7.1+
neverFunction return नहीं करतीPHP 8.1+

7
Variadic Functions — Unlimited Parameters
...
args

Variadic Functions (...)

... (splat/spread operator) से function कितने भी arguments accept कर सकती है। Arguments array में आते हैं। Built-in functions जैसे printf(), implode() इसी तरह काम करते हैं।

PHP 5.6+ Unlimited args Array में आते हैं
VARIADIC — EXAMPLES
<?php
// Basic variadic
function sumAll(int ...$nums): int {
  return array_sum($nums);
}
echo sumAll(1, 2, 3); // 6
echo sumAll(10, 20, 30, 40); // 100

// Mixed — fixed + variadic
function logEvent(string $level, string ...$messages): void {
  foreach ($messages as $msg) {
    echo "[$level] $msg\n";
  }
}
logEvent("ERROR", "DB failed", "Retry...", "Giving up");
// [ERROR] DB failed
// [ERROR] Retry...
// [ERROR] Giving up

// Spread operator — array को arguments में
$numbers = [5, 10, 15];
echo sumAll(...$numbers); // 30 (spread करके pass)
?>

8
Variable Functions — Function Name Variable में
PHP में function का नाम string variable में store करके call कर सकते हो। Callbacks, strategy pattern, dynamic dispatch के लिए।
VARIABLE FUNCTIONS — EXAMPLES
<?php
function add($a, $b) { return $a + $b; }
function mul($a, $b) { return $a * $b; }

$op = "add";
echo $op(5, 3); // 8 — variable function!

$op = "mul";
echo $op(5, 3); // 15

// is_callable() — check करो
if (is_callable($op)) {
  echo $op(10, 2);
}
?>

9
Anonymous Functions — नाम के बिना Functions
λ
anon

Anonymous Functions (Closures)

बिना नाम के functions। Variable में store कर सकते हो, callback में pass कर सकते हो। use keyword से outer scope के variables access करो।

PHP 5.3+ Callbacks use — outer vars
ANONYMOUS FUNCTIONS — EXAMPLES
<?php
// Variable में store
$greet = function($naam) {
  return "नमस्ते, $naam!";
}; // semicolon ज़रूरी!
echo $greet("Rahul"); // नमस्ते, Rahul!

// Callback में pass — array_map
$nums = [1, 2, 3, 4];
$doubled = array_map(function($n) {
  return $n * 2;
}, $nums);
print_r($doubled); // [2, 4, 6, 8]

// use — outer variable access
$discount = 10;
$applyDiscount = function($price) use ($discount) {
  return $price - ($price * $discount / 100);
};
echo $applyDiscount(1000); // 900

// use by reference — outer variable modify
$count = 0;
$counter = function() use (&$count) {
  $count++;
};
$counter(); $counter(); $counter();
echo $count; // 3
?>

10
Arrow Functions — Modern Short Syntax (PHP 7.4+)
fn
=>

Arrow Functions fn() =>

Anonymous functions का short form। fn($x) => $x * 2 — एक line। Outer scope automatically available — use की ज़रूरत नहीं। Functional programming में game changer।

PHP 7.4+ Auto outer scope Single expression

❌ Anonymous function — verbose

$mul = function($x) use ($factor) {
  return $x * $factor;
};

✅ Arrow function — clean!

$mul = fn($x) => $x * $factor;
// $factor auto-captured!
// No use needed!
ARROW FUNCTIONS — EXAMPLES
<?php
// Basic arrow function
$square = fn($n) => $n ** 2;
echo $square(5); // 25

// Outer scope auto-capture
$gst = 0.18;
$addGST = fn($price) => $price + ($price * $gst);
echo $addGST(1000); // 1180

// array_map के साथ — cleanest!
$prices = [100, 200, 300];
$withGST = array_map(fn($p) => round($p * 1.18, 2), $prices);
print_r($withGST); // [118, 236, 354]

// Type hints के साथ
$double = fn(int $n): int => $n * 2;
echo $double(7); // 14

// usort के साथ — price descending
$products = [
  ["name" => "Book", "price" => 450],
  ["name" => "Pen", "price" => 50],
];
usort($products, fn($a, $b) => $b["price"] <=> $a["price"]);
?>
✅ Modern PHP = Arrow Functions everywhere: array_map, array_filter, array_reduce, usort — सब में fn() => use करो। Code 3x shorter और readable होता है।

Quick Reference — Function Styles
StyleSyntaxUse Case
Regularfunction naam($a) { return $a; }General purpose, reusable
Default paramsfunction f($a, $b = 10)Optional parameters
Type hintsfunction f(int $a): stringStrict type safety
Variadicfunction f(...$args)Unknown number of args
Anonymous$f = function($a) { return $a; };Callbacks, closures
Arrow$f = fn($a) => $a * 2;Short callbacks, array_map
By Referencefunction f(&$a)Modify original variable
Named argsf(naam: "Rahul", umar: 25)PHP 8 — order-free calling

🏆
Combined Example — E-Commerce Helper Functions
COMBINED — Real Project Functions
<?php
// 1. Price format — type hints + return type
function formatPrice(float $price, string $currency = "₹"): string {
  return $currency . number_format($price, 2);
}
echo formatPrice(1299); // ₹1,299.00
echo formatPrice(99.5, "$"); // $99.50

// 2. Discount calculate — variadic tax rates
function calcTotal(float $price, float ...$rates): float {
  $tax = array_sum($rates) / 100;
  return round($price + $price * $tax, 2);
}
echo calcTotal(1000, 18); // 1180.00 (18% GST)
echo calcTotal(1000, 9, 9); // 1180.00 (CGST+SGST)

// 3. Cart process — arrow functions
$cart = [
  ["name" => "PHP Book", "price" => 450, "qty" => 2],
  ["name" => "Laravel", "price" => 799, "qty" => 1],
];
$subtotal = array_sum(
  array_map(fn($i) => $i["price"] * $i["qty"], $cart)
);
echo formatPrice(calcTotal($subtotal, 18)); // ₹2,060.62

// 4. Validate email — anonymous closure
$validateEmail = function(string $email): bool {
  return (bool) filter_var(trim(strtolower($email)), FILTER_VALIDATE_EMAIL);
};
var_dump($validateEmail("rahul@gmail.com")); // true
var_dump($validateEmail("not-an-email")); // false
?>
Best Practice: Regular function → reusable logic। Arrow fn() → callbacks। Type hints → always। Default params → optional args।

निष्कर्ष (Conclusion)

PHP Functions code को organize, reusable, और maintainable बनाते हैं। Modern PHP में type hints और arrow functions ज़रूरी हैं — cleaner code, fewer bugs।

function keyword — Define करो। PHP में hoisted होती हैं।

return — Value वापस भेजो। Early exit के लिए guard clauses।

Default params — Right side में। PHP 8 में named arguments।

Type hints — हमेशा use करो। strict_types=1 better।

Variadic (...) — Unlimited arguments। Spread operator से array pass।

Arrow fn() — Callbacks के लिए best। Outer scope auto-available।

🚀 अगला Chapter: Chapter 11: PHP String Formatting & Output Functions — echo, print, printf, sprintf, var_dump, print_r — output control।