1 year ago

#374593

test-img

shuunenkinenbi

PHP: Extend custom database class with the default MySQLi class and a Singleton

Lets say i have a singleton class with the sole purpose of creating singletons:

class singleton {
    public static function getInstance() {
    static $instance = null;
        if($instance === null) {
        $instance = new self;
        }
    return $instance;
    }
}

And a custom database class extending the default one:

class database extends mysqli {
// obvious stuff
}

I now want to be able to have the database class being a children of both, the singleton (for the singleton creation) and the mysqli-class. Basically something like:

class database extends singleton {}
class database extends mysqli {}

According to my research, this is not possible in PHP.

What I'm trying to achieve is, having another method called getInstance() in the database class (so, this method is present in the classes "database" and "singleton", which then first calls the parent constructer (that creates the singleton) and then returns to the child to continue with custom stuff for the corresponding class. Like this:

class singleton {
    public static function getInstance() {
    static $instance = null;
        if($instance === null) {
        $instance = new self;
        }
    return $instance;
    }
}

class database extends singleton {}
class database extends mysqli {
    public static function getInstance() {
    $instance = parent::getInstance();
    
    // Custom code
    
    return $instance;
    }
}

Is that somehow possible? I thought about traits, but you cannot call them as parents.

php

inheritance

mysqli

singleton

extend

0 Answers

Your Answer

Accepted video resources