Subjects

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

What is method overriding in PHP? Does PHP support method overloading? PHP में method overriding क्या है? क्या PHP method overloading सपोर्ट करता है?

Answer

Short Answer

These functions are used to import code from another file into your current script.
include emits a Warning if the file is missing, but continues script execution.
require emits a Fatal Error if the file is missing, and halts script execution immediately.
The _once suffix (include_once / require_once) tells PHP to check if the file was already included previously, and if so, it will not include it a second time (preventing "Cannot redeclare" errors).

Detailed Explanation & Code Example

When building applications, you often separate code into multiple files (e.g., configuration, header, footer).


// If header.php is missing, a warning is shown, but "Page content" is still echoed.
include 'header.php';
echo "Page content";

// If database.php is missing, execution stops completely.
require 'database.php';
echo "Database connected";

Interview Tip

Use require for critical files (like database connections) where the app shouldn't run if the file is missing. Use include for non-critical files (like an optional sidebar).

Method overriding तब होता है जब child class अपने parent class में पहले से डिफाइन method को same नाम और signature के साथ फिर से डिफाइन करती है।

class Shape {
    public function draw(): string { return 'Drawing a generic shape'; }
}
class Circle extends Shape {
    public function draw(): string { return 'Drawing a circle'; }
}
$c = new Circle();
echo $c->draw(); // Drawing a circle (overridden)

PHP Java या C++ की तरह traditional method overloading (same नाम, अलग parameters, compile time पर resolve) सपोर्ट नहीं करता। इसके बजाय PHP magic method __call() से runtime पर dynamic overloading simulate करता है।

class Calculator {
    public function __call($name, $args) {
        if ($name === 'add') {
            return array_sum($args);
        }
    }
}
$calc = new Calculator();
echo $calc->add(1, 2, 3); // 6, किसी भी संख्या के args के साथ काम करता है

इंटरव्यू टिप: यह एक बहुत आम ट्रिक सवाल है - पहले साफ कहें 'PHP true overloading सपोर्ट नहीं करता' फिर __call() workaround समझाएं।

Was this answer clear?