2016-09-12 98 views
0

我將有一個主類和單獨的類,稱爲「插件」。將會有一個Event系統,這些插件將包含觸發事件時調用的方法。在不創建主類的另一個實例或在__construct中提供主類的情況下,是否有任何方式從插件類訪問主類中的函數。PHP存儲/保存類對象

回答

0

使用我創建了以下結構張貼iliaz的答案,它完美的作品

<?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(); 

得到這個輸出

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