Thursday, 9 August 2018

Fix: Class Contains Abstract Methods And Must Therefore Be Declared Abstract Or Implement The Remaining Methods.

This is an error that many beginner PHP developers will come across while they are learning to traverse the world of object orientated programming (that, or they’ve modified an existing codebase, breaking things in the process).
The error in question will read something like:
Fatal error: Class YourClassName contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods
Here is a piece of code that will reproduce the issue:
Run the code above and you’ll undoubtedly receive a fatal error (if you don’t, it’s because your error reporting isn’t enabled).

Why?

When a class contains one or more abstract functions / methods, you must either:
  1. Declare the class as an abstract class or
  2. Implement the methods in the class that is extending your abstract class.
To fix the issue above, we can make one simple change. Instead of writing:
We can declare the class like so:
As you can see, we’ve prepended the keyword abstract to our class declaration.
Some extra notes:
  • Be sure to read up on Class Abstraction in PHP.
  • An abstract class cannot be instantiated. If you try to do so, you will receive a fatal error.

Using Abstract Functions

Firstly, you can’t use abstract functions. You can only implement them. To implement them, you will need to extend the abstract class in question. Here is an example:
As you can see, we’ve created a class called “MyChildClass”, which extends our abstract class “YourClassName”. In this class, we must create the functions “test” and “example, simply because they are defined in our abstract class. Fail to implement them both and you will receive a fatal error.
We can now instantiate the class and use our object like:

0 comments:

Post a Comment