PHP: Fatal error: unable to create abstract class

I have an abstract database class called:

abstract class database {
  protected $value;
}

      

I have created another abstract class

abstract class my_database extends database {
  public function set_value($value) {
    $this->value = $value;
  }
}

      

When I try to use it:

$my_db = new my_database();

      

I get an error:

Fatal error: Cannot instantiate abstract class my_database in ...

      

What I am trying to do: The base of the abstract class has a protected $ value, and I would like to create a wrapper class to be able to change the protected value (temporarily).

How can i do this?

EDIT1: unfortunately earlier when I tried without the abstract my_database I got errors:

- abstract methods and must therefore be declared abstract or implemented
- Abstract function cannot contain body

      

EDIT2: Selecting an abstract word entirely from my_database I got the following error:

Fatal error: class my_database contains 32 abstract methods and must therefore be declared abstract or implement the remaining methods

How can I fix this?

+3


source to share


2 answers


Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. You can read about it in the PHP documentation here: link

Here's an example.

There is an abstract class ( note that abstract methods don't have a body - they CANNOT have a body - it's just a signature ):

abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method. It will be available for all children - they don't have to declare it again.
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

      



Extend your abstract class with a class like this ( note that all abstract methods MUST be defined in a concrete class ):

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

      

Then you can instantiate ConcreteClass1:

$class1 = new ConcreteClass1;

      

+8


source


Your class shouldn't be abstract:

class my_database extends database {
  public function set_value($value) {
    $this->value = $value;
  }
}

      



In OOP, an abstract class cannot be based on just extending it.

0


source







All Articles