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

It will be weird. I have a database class for MySQL and independent classes. For instance:

class users extends MySQL 

this class is a common class for users, so it can be used more than once. But sometimes the class "MySQL_DEBUGGED" is present, and if so, I want to switch from it:

 class users extends MySQL_DEBUGGED 

I want to inherit MySQL_DEBUGGED if present, otherwise the MySQL class. If I put it in a variable, this will result in an error. How to do it?

+4
source share
3 answers

I do not think that you can inherit from a class whose name is not written in a PHP script.


Possible Solution:

  • to define two classes called MySQL in two separate files
  • so that your users class always extends the MySQL class (which means one of these two)
  • Depending on the situation:
    • a file containing the MySQL "production" class,
    • or file containing the MySQL class

Thus, your class always extends the MySQL class, but you enable it.


Basically, in your main file, you would:

 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, of course, will not contain the same material in both files.

+4
source

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

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

I would not recommend it. Conditionally declaring classes seem like a nightmare.

+1
source

The simplest solution is to have an empty "bridge" class and always inherit from it.

Then the only class you would need to declare twice will be empty.

 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 proposed solutions require two copies of your inherited class, which I do not recommend.

+1
source

All Articles