I've created several WordPress plugins that make use of a common class. The plugins should work individually and ideally without the common class installed as a separate plugin, but they can also be activated in the same installation. Now I can prevent loading the class multiple times by doing a class_exists check, but I would like more control over which version of the class is being used, preferably the latest version. This is because it's possible that the user doesn't update one of the plugins and it could be exactly that version of the common class that's used. Is there any way to such a check?
I want to prevent this from happening:
I thought of the following scenario:
However, afaik you cannot unset/override a class by simply defining it again, right?
Some additional info: The classes are already split up into different files. I have thought of just naming the class differently for each plugin, but ultimately they modify the same content, and it gets messy when they do so one after the other (each in a slightly different way if the versions differ).
There is a way for that provided that you add a constant to your class which contains the version. Like this:
class MyCommonClass {
constant VERSION = '2';
// Accessing via INSTANCE
function showVersion() {
echo self::VERSION . "
<br/>";
}
}
// Accessing globally
echo MyCommonClass::VERSION . "
<br/>";
// Programmatically As of PHP 5.3.0
$classname = "MyCommonClass";
echo $classname::VERSION. "
<br/>"; // As of PHP 5.3.0
So checking:
if(class_exists("MyCommonClass")){
if (MyCommonClass::VERSION < 2){
echo "This plugin requires newest version of MyPackage
<br/>";
exit(0);
}
};
You can also divide the classes into files and include them accordingly with class checking.
Finally The bad-practice way is including the class in a file like this:
<?php
$versionOfclass = 2;
if($versionOfClass >= $requiredVersionOfClass) {
class MyClass {
}
}
?>
where $requiredVersionOfClass comes from the php file which includes this.