PHP存储/保存类对象

时间:2016-09-12 04:51:39

标签: php

我将有一个主类和名为'plugins'的单独类。将有一个Event系统,这些插件将包含在触发事件时调用的方法。在没有创建主类的另一个实例或在__construct中提供主类的情况下,有任何方法可以从插件类访问主类中的函数。

2 个答案:

答案 0 :(得分:0)

根据您的php版本,您可以使用Trait。它为继承或甚至不相关的类提供了通用功能。

您可以在此处找到更多信息:

http://php.net/manual/en/language.oop5.traits.php

答案 1 :(得分: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
相关问题