开发者

How to extends use variable

开发者 https://www.devze.com 2023-01-07 01:35 出处:网络
$laca = \'laca开发者_JAVA技巧\'; class laca(){ /*Code*/ } class foo extends $laca; This code doesn\'t work.
$laca = 'laca开发者_JAVA技巧';  
class laca(){ /*Code*/ }  
class foo extends $laca;

This code doesn't work.

I want to make a DB class, and then have some DB driver : mysql, mssql v..v. $db = 'mysql'; So I want the DB class to extend mysql.


Instead of extending the laca class, pass it to the foo class so that it can use it.

class foo {
    function __construct($laca) {
        $this->laca = $laca;
    }

    function storeWidgets($widgets) {
        foreach ($widgets as $widget) {
            $this->laca->saveWidget($widget);
        }
    }
}

...

$laca = new laca();
$foo = new foo($laca);


I think what you really want here is a DBFactory:

class DBFactory {
    public static function create($driver) {
        switch(strtolower($driver)) {
            case 'mysql':
                return new MysqlDB();
        }
    }
}

class MysqlDB{}

$db = DBFactory::create('mysql');

Actually, I think you want to use PDO


A class extends a class, not a variable.

class a {
    // Code
}

class b extends a {
    // Code
}


This does not seem to be possible without the use of eval(). extends needs a properly qualified class name and cannot be a variable in any circumstance.


I don't think you're doing this right.

What you should do is create a hierarchy: have a base DB abstract class that defines common behavior applicable to all database types, then have a separate class for each database extend the base class. In other words, something like this:

abstract class DB {
    public function __construct($host, $username, $password) {
        $this->connect($host, $username, $password);
    }
    abstract public function connect($host, $username, $password);
    abstract public function query($sql);
}

class MySQL extends DB {
    public function connect($host, $username, $password) {
        //...
    }
    public function query($sql) {
        //...
    }
}

Then, depending on which database you need, create an instance of the proper class:

if ($dbtype == 'mysql') {
    $DB = new MySQL($host, $username, $password);
}
else if ($dbtype == 'mssql') {
    $DB = new MySQL($host, $username, $password);
}
//...


I personally use this anywhere it fits. Sometimes I even put the class identifier behind this. Reason, if you have listener, thread or other inner class inside your class, you might feel better and clearer with this to avoid conflicts.

0

精彩评论

暂无评论...
验证码 换一张
取 消