I mean can we directly use interface class inside main class as a constructor.
Asked
Active
Viewed 590 times
-2
-
2Really not sure what you're asking here but why don't you simply try it and see if it works? – Phil Oct 23 '17 at 23:11
-
Do you mean like [Java's anonymous classes](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html), ie `$impl = new SomeInterface { /* interface methods here */ };`? PHP 7 has [anonymous classes](http://php.net/manual/language.oop5.anonymous.php). Is that what you're after? – Phil Oct 23 '17 at 23:13
-
possible you are talking about [nested or inner class](https://stackoverflow.com/questions/16424257/nested-or-inner-class-in-php) – Sachin Kumar Oct 23 '17 at 23:15
-
I mean can we instantiate interface class in PHP as null. TestInterface $test=null; – Anonymous Oct 23 '17 at 23:17
-
Since PHP variables aren't typed, you cannot do that. You can use `$test = null;` though – Phil Oct 23 '17 at 23:21
1 Answers
0
No, you can't instantiate an Interface in PHP.
<?php
interface TestError {
public function test() {
print "Bye!"; // Fatal error: Interface function Test::test() cannot contain body
}
}
interface Test {
public function test();
}
class Main {
public function __construct () {
$test = new Test(); // Fatal error: Cannot instantiate interface
}
}
$main = new Main();
?>

aabilio
- 1,697
- 12
- 19