I will have one main class and separate classes called 'plugins'. There will be an Event system that these plugins will contain methods that get called when an event is triggered. Without creating another instance of the main class or providing the main class in __construct is there any way of accessing functions in the main class from the plugins classes.
Depending on your php version you can use a Trait. It provides common functionality to inherited or even unrelated class.
You can find more here:
Using the answer posted by iliaz I created the following structure and it works perfectly
<?php
class MainClass {
use MainTrait;
function __construct() {
$this->fromMainClass();
$this->initPlugins();
}
}
trait MainTrait {
private function initPlugins(){
new PluginClass();
}
function fromMainClass(){
echo "This is from the main class.<br>";
}
function callFromPlugin(){
echo "This is from the plugin in the main class<br>";
}
}
class MainPluginClass {
use MainTrait;
function pluginTest(){
echo "This is from the plugin in the main PLUGIN class<br>";
}
}
class PluginClass extends MainPluginClass{
function __construct() {
$this->callFromPlugin();
$this->pluginTest();
$this->plugin();
}
function plugin(){
echo "This is from the plugin<br>";
}
}
new MainClass();
Getting this output
This is from the main class.
This is from the plugin in the main class
This is from the plugin in the main PLUGIN class
This is from the plugin
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.