How to get an instance of you Plugin's Main class in other classer without using a constructor

Discussion in 'Facepalm' started by Darku, Oct 9, 2018.

  1. Darku

    Darku Spider Jockey

    DISCLAIMER: This is just a small guide and probably not very helpfull for most people. It explains a simple concept that most experienced developers are already fammilar with. It may contain "poor quality", "facepalm" or "useless" content.

    So, you just made a task which does not allow you to serialize object instances in the constructor? You are stuck and don't know how to reach your plugin's main class without using/modifying the constructor?

    Well, its actually not that hard. The simple solution to your problem is a static function. It can give a main class' instance to any other class without having to touch the constructor at all.

    To begin with, some changes to your main class are necessary.
    First, create a static variable for your main class' instance like this:

    private static $instance = null;
    Once we have created our variable, we need to fill it with the main class' instance.
    You can for example do this in the onEnable() event handler like this:

    public function onEnable()
      self::$instance = $this;
    So finally, we need to create the actual static function which returns the main class' instance to other classes if called. For example:
    public static function getPluginInstance()
      return self::$instance;

    Now we're done on the main class' side.
    Now to acatually get your main class' instance in other calsses, make sure you
    have imported your main class in the imports of that class.
    To then gain the instance, simply write:

    <your main class' name>::getPluginInstance()
    to gain a variable simmilar to the $this in your main class.
    from there, you can also access the server, config, logger and everxthing your might need.

    Most of the example code is taken from PocketMine's Server class.
    You can visit it to find out more about instances.

    I hope this small guide was somewhat usefull for some people, i would appreciate any constructive feedback ;).
  2. Seeker

    Seeker Spider Jockey

    Why should $instance be null?...
    Here you go:

    /** @var ClassName */ //now $instance is this class
    private static $instance;
    public static getInstance() : self{

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.