Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is abstraction in PHP and how does it differ from encapsulation? PHP में abstraction क्या है और यह encapsulation से कैसे अलग है?

Answer

Short Answer

Variable scope defines where a variable can be accessed or modified within a script. PHP has three main scopes: Local (inside a function), Global (outside a function), and Static (persists data across function calls).

Detailed Explanation & Examples

1. Local Scope

Variables declared inside a function are local to that function. They cannot be accessed from outside.


function testLocal() {
    $age = 25; // Local scope
    echo $age;
}
testLocal(); // Outputs: 25
// echo $age; // Error: Undefined variable

2. Global Scope

Variables declared outside of any function have global scope. By default, they cannot be accessed inside a function unless you use the global keyword.


$name = "Prepiq"; // Global scope

function testGlobal() {
    global $name; // Import the global variable
    echo $name;
}
testGlobal(); // Outputs: Prepiq

3. Static Scope

Normally, when a function finishes executing, all of its local variables are deleted. A static variable is NOT deleted. It remembers its value from the previous time the function was called.


function counter() {
    static $count = 0; // Only initialized once
    $count++;
    echo $count . " ";
}

counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3

Abstraction implementation की जटिलता छुपाता है और सिर्फ ज़रूरी चीज़ें expose करता है, आमतौर पर abstract classes या interfaces से। Encapsulation access modifiers से internal data छुपाता है। दोनों related हैं पर अलग समस्याएं हल करते हैं।

पहलूAbstractionEncapsulation
फोकस'कैसे' किया जाता है छुपाता है (implementation)'क्या' डेटा दिखता है छुपाता है (state)
कैसे हासिलAbstract classes, interfacesAccess modifiers (private/protected), getters/setters
सवाल जवाब देता हैयह object क्या करेगा?इस object का डेटा कैसे सुरक्षित है?
abstract class PaymentGateway {
    abstract public function charge(float $amount): bool;
}

class StripeGateway extends PaymentGateway {
    public function charge(float $amount): bool {
        // असली Stripe API call यहाँ छुपी है
        return true;
    }
}

इंटरव्यू टिप: कहें abstraction design के बारे में है (क्या operations हैं), encapsulation सुरक्षा के बारे में है (डेटा कैसे guard है) - दोनों साथ काम करते हैं, विरोध में नहीं।

Was this answer clear?