This is an error that many beginner PHP developers will come across while they are learning object orientated programming.
This kind of error can occur if you are attempting to modify an existing code base.
The error in question will read as follows.
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.
<?php class YourClassName{ /** * Abstract method. */ abstract public function test(); /** * Abstract method. */ abstract public function example(); }
If you run the code above, you will undoubtedly receive a fatal error. If you do not see an error message, then it is because of your error display settings.
Why is this error happening?
When a class contains one or more abstract functions / methods, you must do one of the following.
- Declare the class as an abstract class.
- 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:
<?php class YourClassName{
We can declare the class like so:
<?php abstract class YourClassName{
As you can see, we’ve added the keyword abstract to our class declaration.
Some extra notes.
- Be sure to read up on Class Abstraction in PHP. Do not blindly add the keyword abstract to an existing code base.
- An abstract class cannot be instantiated. In other words, you will not be able to create an object from it. If you try to do so, you will receive a fatal error.
Using abstract functions in PHP.
Firstly, you cannot use abstract functions directly. You can only implement them. To implement them, you will need to extend the abstract class in question.
Take a look at the following example, where we extend our abstract class.
/** * Extending our abstract class. */ class MyChildClass extends YourClassName{ /** * Implementing the abstract method test() */ public function test(){ //do something } /** * Implementing the abstract method example() */ public function example(){ //do something } }
As you can see, we have created a class called “MyChildClass”, which extends our abstract class “YourClassName”.
In this class, we must also create the functions “test” and “example“, simply because they exist in our abstract class. If we fail to implement these functions, then we will receive a fatal error.
Finally, we can now instantiate the class and use our object like so.
$myChildClass = new MyChildClass(); $myChildClass->test();
Bingo!