PHP Fetal Error: Cannot instantiate interface (solution)

Quick solution to a rare but not so obvious problem when instantiating classes that are manually included.

106 views

Edited: 2021-08-23 11:43

Fatal error: Uncaught Error: Cannot instantiate interface keyworld\lib\db\db_interface in /var/www/test/test.php:29 Stack trace: #0 {main} thrown in /var/www/test/test.php on line 29

Getting a little rusty? This problem is easy to solve once you realize what is happening. It might happen when you are importing external PHP code that is part of another project and namespace, and you have made a mistake somewhere.

While the error message does not appear to be very helpful at first sight, if you think about it, the error actually tells you exactly what is wrong:

... Cannot instantiate interface ...

It tells you that you are trying to instantiate an interface somewhere in your code. The problem with doing that is that interfaces should not be instantiated — instead you need to pick the specific class that implements the interface, and then instantiate that directly.

I recently made this mistake myself, probably because it has been a while since I tried to instantiate a class that implements an interface manually. Once I realized my mistake, then it was an "ahhh, I already know this!" moment, and the problem was easily fixed.

Hopefully that helps.

Tell us what you think:

  1. How to create a custom error handler for PHP that handles non-fetal errors.
  2. The fread function can be dangerous when used inside a loop in PHP, find out how to secure it in this article.
  3. How to show or hide error messages in PHP. There are several ways to do this; from within the PHP scripts themselves, from php.ini, or from changing Apache configuration files.
  4. E_STRICT will only show you warnings about deprecated PHP features and things that might not be future-proof, it will not show you notices or warnings; E_ALL includes everything, and that includes E_STRICT messages.
  5. Developers can trigger custom PHP error messages using the trigger_error function; but throwing an exception is often better.

More in: PHP Errors