简体   繁体   中英

Php extends from different class runtime (extends as variable?)

This is going to be strange. I have a database class for MySQL, and independent classes. For example:

class users extends MySQL

this class is a general class for users, so that it can be used more times. But occasionally, an "MySQL_DEBUGGED" class is present, and if so, I want to extend from it:

class users extends MySQL_DEBUGGED

I want to inherit MySQL_DEBUGGED if present, otherwise MySQL class. If I put it into variable, it drops an error. How to do it?

I don't think you can inherit from a class which name is not written in the PHP script.


A possible solution would be:

  • to define two classes, both called MySQL , in two separate files
  • make your users class always extend the MySQL class (which means one of those two)
  • Depending on the situation, include:
    • the file that contains the "production" MySQL class,
    • or the file that contains the "development" MySQL class

This way, your class always extends a MySQL class -- but you'll include the right one .


Basically, in your main file, you'd have:

if (DEBUG) {
    require __DIR__ . '/MySQL-debug.php';
}
else {
    require __DIR__ . '/MySQL-production.php';
}

class users extends MySQL {
    // ...
}

And both MySQL-debug.php and MySQL-production.php will contain a class called MySQL -- which would not contain the same stuff in both files, of course.

All you need to do is use the class_exists() function.

if (class_exists('MySQL_DEBUGGED')) {
    class users extends MySQL_DEBUGGED {
        ....
    }
} else {
    class users extends MySQL {
        ....
    }
}

I wouldn't recommend it though. Conditionally declaring classes seems like a nightmare.

The easiest solution would be to have an empty "bridge" class and inherit always from that one.

Then, the only class that you would need to have declared twice would be the empty one.

if (class_exists('MySQL_DEBUGGED')) {
  class MySQLBridge extends MySQL { }
} else {
  class MySQLBridge extends MySQL_DEBUGGED { }
}

class User extends MySQLBridge {
  // ... your code ...
}

And finally on your pages:

require_once('User.php');
$user = new User();

Other suggested solutions require you to have two copies of your inherited class, which I don't recommend.

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