Explain encapsulation in PHP with an example. PHP में encapsulation एक उदाहरण के साथ समझाएं।
Short Answer
Both echo and print are language constructs used to output data to the screen. The main differences are that echo can take multiple parameters and has no return value, making it marginally faster. print can only take a single argument and always returns 1, meaning it can be used in expressions.
Comparison Table
| Feature | echo |
print |
|---|---|---|
| Return Value | None (void) | Returns 1 |
| Multiple Arguments | Supported (e.g., echo "a", "b";) |
Not Supported |
| Speed | Slightly faster | Slightly slower |
| Usage in Expressions | No | Yes (e.g., $val = print("Hi");) |
Code Example
// echo multiple strings
echo "Hello ", "World", "!";
// print returning a value (useful in ternary operators)
$isPrinted = print("Hello World!"); // Outputs: Hello World!
echo $isPrinted; // Outputs: 1
// echo inside an expression will cause a Syntax Error
// $val = (echo "test"); // ERROR!
Interview Tip
In modern PHP development, always use echo. The speed difference is microscopic, but echo is the universally accepted standard in the PHP community.
Encapsulation का मतलब है object के internal data तक सीधा access रोकना और public methods (getters/setters) के ज़रिए controlled access देना। यह data integrity को सुरक्षित रखता है।
class BankAccount {
private float $balance = 0;
public function deposit(float $amount): void {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function getBalance(): float {
return $this->balance;
}
}
$acc = new BankAccount();
$acc->deposit(500);
echo $acc->getBalance(); // 500
// $acc->balance = -1000; // Error: private property access नहीं हो सकताEncapsulation के बिना, कोई भी कोड सीधे $acc->balance = -1000 सेट कर सकता था, business rules को bypass करते हुए। private और controlled deposit() method से invalid states रोके जाते हैं।
इंटरव्यू टिप: बताएं यह 'tell, don't ask' सिद्धांत की बुनियाद है - objects को raw internal state नहीं, behavior expose करना चाहिए।
Was this answer clear?