PHP Functions क्या है?
Complete Guide in Hindi
PHP Functions की पूरी जानकारी — Function define करना, Parameters, Return Values, Default Values, Type Hints, Variadic Functions, Anonymous Functions, और Arrow Functions।
📋 इस Article में क्या-क्या है
- Function क्या है?
- Function Define करना
- Parameters और Arguments
- Return Values
- Default Parameter Values
- Type Hints (PHP 7+)
- Variadic Functions (...)
- Variable Functions
- Anonymous Functions
- Arrow Functions (PHP 7.4+)
Function एक reusable code block है जो एक specific task करता है। एक बार define करो, बार-बार call करो। Code duplication खत्म, errors कम, maintenance आसान।
❌ बिना Function — Repetitive Code
$area1 = 5 * 3;
$area2 = 8 * 4;
$area3 = 10 * 6;
✅ Function से — DRY Code
area(5, 3);
area(8, 4);
area(10, 6);
// function body
return $result; // optional
}
// Call करना:
functionName( $arg1, $arg2 );
// 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!"; }
?>
// 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
?>
// 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
?>
// 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 नहीं
?>
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 Hint | Accepts | PHP Version |
|---|---|---|
| int | Integer numbers | PHP 7+ |
| float | Decimal numbers | PHP 7+ |
| string | Text | PHP 7+ |
| bool | true/false | PHP 7+ |
| array | Arrays | PHP 7+ |
| ?int | int या null | PHP 7.1+ |
| int|float | Union types | PHP 8+ |
| mixed | Any type | PHP 8+ |
| void | Return type — कुछ नहीं | PHP 7.1+ |
| never | Function return नहीं करती | PHP 8.1+ |
// 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)
?>
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);
}
?>
// 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
?>
❌ Anonymous function — verbose
return $x * $factor;
};
✅ Arrow function — clean!
// $factor auto-captured!
// No use needed!
// 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"]);
?>
| Style | Syntax | Use Case |
|---|---|---|
| Regular | function naam($a) { return $a; } | General purpose, reusable |
| Default params | function f($a, $b = 10) | Optional parameters |
| Type hints | function f(int $a): string | Strict type safety |
| Variadic | function 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 Reference | function f(&$a) | Modify original variable |
| Named args | f(naam: "Rahul", umar: 25) | PHP 8 — order-free calling |
// 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
?>
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।