What are access modifiers in PHP (public, protected, private)? PHP में access modifiers क्या हैं (public, protected, private)?
Short Answer
A superglobal is a built-in array variable in PHP that is accessible from anywhere in your script—inside functions, classes, or loops—without needing to use the global keyword.
Detailed Explanation
In PHP, normal variables have a restricted scope. If you define a variable outside a function, you cannot access it inside a function unless you pass it as a parameter or use the global keyword. Superglobals bypass this rule.
The primary PHP superglobals are:
$_GET: Variables passed via URL parameters.$_POST: Variables passed via HTTP POST (like form submissions).$_SESSION: Session variables stored on the server.$_COOKIE: Cookie variables sent by the client browser.$_SERVER: Server and execution environment information (e.g., headers, paths, script locations).$_REQUEST: Combines GET, POST, and COOKIE data.$_FILES: Data related to uploaded files via HTTP POST.
Code Example
// Even though this is inside a function, we can access $_SERVER without any extra code
function printUserIP() {
echo "Your IP is: " . $_SERVER['REMOTE_ADDR'];
}
printUserIP();
Access modifiers properties और methods की visibility control करते हैं, encapsulation लागू करते हुए।
| Modifier | कहाँ से एक्सेसिबल |
|---|---|
| public | कहीं से भी - class के अंदर, subclasses, और बाहरी कोड |
| protected | class और किसी भी subclass के अंदर (बाहर से नहीं) |
| private | सिर्फ उसी class के अंदर जहाँ declare हुआ, subclass में भी नहीं |
class User {
public string $username;
protected string $email;
private string $password;
}
class Admin extends User {
public function show() {
echo $this->username; // ठीक
echo $this->email; // ठीक, protected
// echo $this->password; // Error, private
}
}इंटरव्यू टिप: properties के लिए default private रखने की सलाह दें, access सिर्फ explicit public methods से दें - इससे बाहरी कोड तोड़े बिना internal refactoring आसान रहती है।
Was this answer clear?