Subjects

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

Explain polymorphism in PHP with an example. PHP में polymorphism एक उदाहरण के साथ समझाएं।

Answer

Short Answer

== (Equal) checks if two values are equal after performing "type juggling" (converting them to the same data type).
=== (Identical / Strict Equal) checks if two values are equal AND are of the exact same data type. It does NOT convert types.

Detailed Explanation & Code Example

In PHP, type juggling can lead to dangerous, unexpected bugs. It is a best practice to almost always use strict comparison (===).


$a = 5;      // Integer
$b = "5";    // String

// Loose Comparison (==)
if ($a == $b) {
    echo "True! PHP converted the string '5' to an integer for comparison.";
}

// Strict Comparison (===)
if ($a === $b) {
    echo "This will NOT execute.";
} else {
    echo "False! They look the same, but one is an Integer and one is a String.";
}

Common Pitfall Example

Consider the strpos() function, which returns the numeric index of a substring, or false if it's not found.


$str = "Hello World";
$position = strpos($str, "Hello"); // Returns 0 (index 0)

// BAD CODE: 0 == false is TRUE in loose comparison!
if ($position == false) {
    echo "Not found!"; // This incorrectly executes because 0 == false
}

// GOOD CODE: 0 !== false in strict comparison.
if ($position === false) {
    echo "Not found!";
}

Polymorphism का मतलब है same method नाम अलग-अलग class में अलग व्यवहार करता है। PHP में यह method overriding और interfaces से हासिल होता है।

interface Shape {
    public function area(): float;
}

class Circle implements Shape {
    public function __construct(private float $radius) {}
    public function area(): float { return pi() * $this->radius ** 2; }
}

class Rectangle implements Shape {
    public function __construct(private float $w, private float $h) {}
    public function area(): float { return $this->w * $this->h; }
}

function printArea(Shape $shape) {
    echo $shape->area();
}
printArea(new Circle(5));
printArea(new Rectangle(4, 6));

printArea() फंक्शन को फर्क नहीं पड़ता कौन सा shape मिला - वह सिर्फ area() call करता है, और हर class अपना implementation देती है। यही polymorphism है।

इंटरव्यू टिप: बताएं इस design से बाद में नया shape (जैसे Triangle) बिना printArea() बदले जोड़ा जा सकता है - Open/Closed Principle।

Was this answer clear?