Interface एक class का blueprint होता है। Class की तरह ही interface में methods होते हैं, लेकिन variables नहीं होते।
दूसरे शब्दों में कहें तो, “Interface एक structure की तरह होता है। यह एक class को बताता है कि उसे कौन-कौन से methods implement करने हैं।”
Interface में declare किए गए methods abstract होते हैं, यानी इनका कोई implementation नहीं होता, केवल method का signature (नाम, पैरामीटर) होता है।
interface को class के अंदर define किया जाता है, लेकिन इसे खुद से object के रूप में instantiate नहीं किया जा सकता।
Interface का मुख्य उद्देश्य यह सुनिश्चित करना है कि class के अंदर implement किए गए methods एक समान signature के साथ हों। यह हमें यह गारंटी देता है कि किसी class में implement किए गए methods बिल्कुल वही हों जो interface में declare किए गए हैं।
Interface को Define (डिफाइन) करना
PHP में interface को interface keyword के द्वारा define किया जाता है। इसे class की तरह ही define किया जाता है, लेकिन इसमें कोई भी method body नहीं होती। सिर्फ method का signature होता है।
इसका उदाहरण:–
<?php
interface Animal {
public function sound(); // method signature
}
?>
इस उदाहरण में Animal नाम का interface डिफाइन किया गया है, जिसमें sound() नाम के method का signature दिया गया है। इस interface को implement करने वाली class को sound() method को डिफाइन करना होगा।
Interface को Implement करना
जब कोई क्लास interface को implement करती है, तो उस class को interface में declare किए गए सभी methods को define करना होता है। यदि कोई method डिफाइन नहीं किया जाता, तो PHP एक error दिखाएगा।
इसका उदाहरण:-
<?php
interface Animal {
public function sound();
}
class Dog implements Animal {
public function sound() {
echo "Bark";
}
}
class Cat implements Animal {
public function sound() {
echo "Meow";
}
}
?>
यहाँ पर, Dog और Cat दोनों class ने Animal interface को implement किया है और दोनों class में sound() method को define किया गया है। Dog class में “Bark” और Cat class में “Meow” प्रिंट होगा।
इसे पढ़ें:–
निवेदन:- अगर आपके कुछ सवाल हो तो उसे नीचे comment करके बताइए, हम उसे एक दो दिन के अंदर इस वेबसाइट के अंदर publish कर देंगे। जिससे आपको exam में लाभ होगा।