What is type juggling / type casting in PHP? PHP में type juggling / type casting क्या है?
Short Answer
By default, PHP passes variables to functions by value, meaning the function receives a copy of the variable; changing it inside the function does not affect the original. Passing by reference (using the & symbol) passes the actual memory address, so changing the variable inside the function alters the original variable.
Detailed Explanation & Code Example
1. Pass by Value (Default behavior)
function addTen($number) {
$number += 10;
}
$myAge = 25;
addTen($myAge);
echo $myAge;
// Output: 25. (The original variable is untouched)
2. Pass by Reference
Notice the & symbol before the parameter in the function signature.
function addTenByRef(&$number) {
$number += 10;
}
$myAge = 25;
addTenByRef($myAge);
echo $myAge;
// Output: 35. (The original variable was modified directly)
Interview Tip
Always note that PHP objects are passed by reference-like behavior by default. If you pass an object into a function and modify its properties, the original object outside the function will reflect those changes without needing the & symbol.
PHP कॉन्टेक्स्ट के आधार पर वेरिएबल के टाइप को अपने आप बदल देता है — इसे type juggling कहते हैं। Type casting तब होता है जब डेवलपर खुद conversion करता है।
// Type juggling (automatic)\n$sum = "5" + 3; // int(8)\n\n// Type casting (explicit)\n$num = (int) "42abc"; // 42\n$str = (string) 42; // "42"\n$bool = (bool) ""; // false\n$arr = (array) "hi"; // ["hi"] | Cast | Syntax |
|---|---|
| Integer | (int) या (integer) |
| Float | (float) या (double) |
| String | (string) |
| Boolean | (bool) या (boolean) |
| Array | (array) |
इंटरव्यू टिप: क्लासिक PHP 8 गोचा बताएं: "abc" == 0 अब false है (PHP 8 से पहले true था) — एक आम ट्रिक सवाल।
Was this answer clear?