__call मेथड
__call मेथड PHP में एक मैजिक मेथड है, जो क्लास की मौजूद नहीं होने वाली या अनुपलब्ध मेथड को एक्सेस करने के प्रयास पर स्वचालित रूप से कॉल होती है। यह पहले पैरामीटर के रूप में कॉल की गई मेथड का नाम लेती है, और दूसरे के रूप में - आर्गुमेंट्स की एक ऐरे।
सिंटैक्स
public function __call(string $name, array $arguments) {
// इम्प्लीमेंटेशन
}
उदाहरण
आइए एक क्लास बनाते हैं जिसमें __call मेथड हो, जो मौजूद नहीं होने वाली सभी मेथड्स के कॉल को इंटरसेप्ट करेगी:
<?php
class Test {
public function __call($name, $args) {
echo "Called method: " . $name . "\n";
echo "Arguments: ";
print_r($args);
}
}
$test = new Test();
$test->nonExistentMethod('a', 'b', 123);
?>
कोड एक्सेक्यूशन का रिजल्ट:
Called method: nonExistentMethod
Arguments: ['a', 'b', 123]
उदाहरण
आइए __call की मदद से एक साधारण मेथड डेलीगेटर इम्प्लीमेंट करते हैं:
<?php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
class Math {
private $calculator;
public function __construct() {
$this->calculator = new Calculator();
}
public function __call($name, $args) {
if (method_exists($this->calculator, $name)) {
return call_user_func_array(
[$this->calculator, $name],
$args
);
}
throw new Exception("Method $name not found");
}
}
$math = new Math();
echo $math->add(2, 3);
?>
कोड एक्सेक्यूशन का रिजल्ट:
5
यह भी देखें
-
__callStaticमेथड,
जो स्टैटिक मेथड्स के कॉल को इंटरसेप्ट करती है -
__getमेथड,
जो मौजूद नहीं होने वाले प्रॉपर्टीज के एक्सेस को इंटरसेप्ट करती है