Interfaces cant be instantiated , and interfaces do not have methods bodys so how that code works ? (to manage Exception and Error at same time in php 7 we use Throwable cause Exception and Error both implement a new interface )
try { // Code that may throw an Exception or Error. } catch (Throwable $t) { // Handle exception }
Advertisement
Answer
Exception
and Error
implement the interface Throwable
. In fact there is a whole hierarchy for Errors in PHP. You can catch a specific type of error or you can go up the tree and catch more generic errors. Throwable
is the base interface and is going to catch all errors in the hierarchy.
When type hinting with OOP you do not need to use the exact type. You can use the base interface or parent type. For example.
interface MyInterface { } class A implements MyInterface { } function doSomething(MyInterface $obj) { // something } doSomething(new A);
This code works and accepts the object of class A
even if the type expected is an interface MyInterface
.