tags:

views:

42

answers:

6
$laca = 'laca';  
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. Sorry for my bad English.

A: 

A class extends a class, not a variable.

class a {
    // Code
}

class b extends a {
    // Code
}
Kerry
I think what the OP wants to do is extend a class whose name is not known until runtime.
musicfreak
Ah okay, makes more sense
Kerry
+3  A: 

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);
Sjoerd
A: 

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.

Pekka
+1  A: 

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

Dennis Haarbrink
This is all i need, thanks you so much
Snoob
A: 

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);
}
//...
musicfreak
I want the user is set a variable which db type use, then them can use it on base DB: class DB{ $db = 'mysql'; -> Then use MYSQL class }
Snoob
A: 

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.

Nemo