php强制执行扩展类的类型


php enforce type of extending class

php中是否有任何方法可以确保一个类只能由一个类扩展?

我有一些代码说明了我要做的事情,基本上我有一个DB管理器类和一个由管理器类扩展的DB查询类。我想做的是确保DB查询类只能由DB管理器类使用。

下面的代码可以工作,但看起来很粗糙。在代码中,我用一个检查类名的抽象函数来维护查询类抽象,或者我可以简单地在查询类中将所有Manager函数声明为抽象(这似乎很糟糕)。如果有一种比我下面的代码更简单的方法,那将非常有用。。。

abstract class DB_Query {
    private static $HOST = 'localhost';
    private static $USERNAME = 'guest';
    private static $PASSWORD = 'password';
    private static $DATABASE = 'APP';

//////////
/* USING ABSTRACT FUNCTION HERE TO ENFORCE CHILD TYPE */
abstract function isDB();
/* OR USING ALTERNATE ABSTRACT TO ENFORE CHILD TYPE */
    abstract function connect();
    abstract function findConnection();
    abstract function getParamArray();
//////////

    private function __construct() { return $this->Connect(); }
    public function Read($sql) { //implementation here }
    public function Query($sql) { //implementation here }
    public function Fetch($res, $type='row', $single='true') { //implementation here }
}
class DB extends DB_Query {
    public $connections = array();
    public static $instance;
    public function isDB() {
        if (get_parent_class() === 'Database' && get_class($this)!=='DB') {
            throw new 'Exception('This class can''t extend the Database class');
        }
    }
    public function connect($host=null,$user=null,$pass=null,$db=null) { //implementation here }
    function findConnection($user, $password=null) { //implementation here }
    public function getParamArray($param) {}
    public function threadList() {}
    public function getThread($threadId=null) {}
    public static function Singleton() { //implementation here }
    private function __construct() { //implementation here }
}

我会将DB_Query的构造函数标记为final,并以它检查实例并引发一些异常的方式实现它。像这样的

class Base {
    final function __construct() {
         if (!$this instanceof Base && !$this instanceof TheChosenOne) {
               throw new RuntimeException("Only TheChosenOne can inherit Base");
         }
         /**
          * use this function as constructor
          */
         $this->__internal_base_construct();
    }
    protected function __internal_base_construct() {
     // constructor code
    }
}

但你的问题相当奇怪,在几个方面打破了OOP的概念。只需将其合并为一个类,并使用最终类指令。

http://php.net/manual/en/language.oop5.final.php

class Database_Query extends Database {
    public static $instance;
    public function Query($sql) {}
    public function Fetch($res, $type='row', $single='true') {}
    public static function Singleton() {}
    private function __construct() {
        $this->link = $this->connect()->find('guest')->getLink();
    }
}