简体   繁体   中英

abstract class extends abstract class in php?

I am working on a simple abstract database class. In my usage of this class, I'll want to have some instance be a singleton. I was thinking of having a abstract class that is not a singleton, and then extend it into another abstract class that is a singleton. Is this possible? Recommended?


Edit: I want to have two abstract that are practically identical, except one is a singleton. So the only difference will be that one will have all the functions of the other, but will have the other properties and methods that make it behave like a singleton.

I'd like to have one base class code base for this so as I make changes, I don't have to keep two files in sync.

In the way that I do things, I believe that there's no use for an abstract singleton. This is because,

1) What you want to be a singleton is the final class you instantiate for use within the application whether it'd be a library, model, controller or view and NOT the abstract.

2) Adding the singleton method is easy and can be written in 8 lines. See below.

protected static $_instance;
public static function getInstance()
{
    if (!isset(self::$_instance)) {
        self::$_instance = new self();
    }
    self::$_instance;
}

3) PHP 5.3 below version doesn't support late static binding. This will result in instantiating the abstract class instead of the final class inheriting it and will not function as expected, as already mentioned by Gordon and nuqqsa. So, for backward compatibility, better avoid it.

The implementation of the singleton pattern must satisfy two requirements:

  1. It must provide a mechanism to access the singleton class instance without creating a class object
  2. It must persist the singleton object so that it is not instantiated more than once

As long as that's provided, the variations are multiple. There's nothing wrong with making the class abstract extending from another abstract, if that's what you need. BUT, as @Gordon says, be aware that overriding static methods/properties causes peculiar behaviours in PHP < 5.3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM