Subjects

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

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

Answer

Short Answer

PHP supports 8 primitive data types categorized into scalar, compound, and special types. These include String, Integer, Float, Boolean (Scalar), Array, Object (Compound), and NULL, Resource (Special).

Code Example: Common Data Types

Since PHP is a loosely typed language, you do not need to explicitly declare data types when creating variables. PHP automatically converts the variable to the correct data type based on its value.


// Scalar Types
$name = "Prepiq";       // String
$age = 25;              // Integer
$price = 19.99;         // Float (Double)
$isActive = true;       // Boolean

// Compound Types
$colors = ["Red", "Blue", "Green"]; // Array
$user = new stdClass();             // Object

// Special Types
$connection = null;     // NULL
// $file = fopen("test.txt", "r");  // Resource

Important Points

  • Loosely Typed: You can change a variable from an integer to a string simply by reassigning it.
  • Type Juggling: PHP will automatically attempt to convert types during comparisons (e.g., "1" == 1 is true). This is why using strict comparison (===) is recommended.

Inheritance एक class (child) को दूसरी class (parent) की properties और methods extends कीवर्ड से reuse करने देता है, कोड duplication से बचाते हुए।

class Animal {
    protected string $name;
    public function __construct(string $name) { $this->name = $name; }
    public function eat(): string { return $this->name . ' is eating'; }
}

class Dog extends Animal {
    public function bark(): string { return $this->name . ' says Woof!'; }
}

$dog = new Dog('Rex');
echo $dog->eat();  // Rex is eating (inherited)
echo $dog->bark(); // Rex says Woof! (अपना method)
टर्ममतलब
extendsparent class से inherit करने का कीवर्ड
parent::parent class का method या constructor call करने के लिए
PHP सीमासिर्फ single inheritance allowed (एक parent class); ज़्यादा के लिए interfaces/traits इस्तेमाल करें

इंटरव्यू टिप: बताएं PHP multiple class inheritance सपोर्ट नहीं करता, लेकिन traits यह कमी पूरी करते हैं।

Was this answer clear?