1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

Using Configs with consts

Discussion in 'Development' started by xanb, Jul 20, 2021.

  1. xanb

    xanb Spider

    Messages:
    6
    How could I add a configuration to a const? My current code is

    PHP:
    public const ERROR $this->getConfig->get("error-message");
    However it doesn't work. Prior to adding the config it was just:

    PHP:
    public const ERROR "Error:";
    What should I change for this to work?
     
  2. Primus

    Primus Zombie Pigman

    Messages:
    749
    You can't define class constants in runtime.

    PHP:
    public static $ERROR;

    static::
    $ERROR $this->getConfig()->get('error-message');
    At that moment when constant is assigned with its value, $this variable is not even initialized. Therefore getting value out of Config object is not possible.
     
  3. UPL

    UPL Silverfish

    Messages:
    15
    Hi!
    PHP:
    // Making it.
    public const ERROR$this->getConfig->get("error-message"); // You're trying to get plugin configuration, and in plugin configuration isn't the error
    I remind you using this code:

    PHP:
    // Before start, you need to use Config class:

    use pocketmine\utils\Config;

    // This should be in "onEnable" function, replacing the another config

    $this->getServer()->getPluginManager()->registerEvents($this$this);
    $this->database = new Config($this->getDataFolder() . "stats.yml"Config::YAML, array( 
        
    "last-error" ""
    ));
    $this->database;

    // When an error happens, you use this code to set error
    $this->database->set("last-error",  "Error Message Here");

    // To get the error with a const, you use this:
    public const ERROR$this->database->get("last-error");
    With this, in plugin_data folder you will see a file named stats.yml, when an error happens, you will se a change in the file and it should be like this:
    Code:
    ---
    last-error: "Last Error Message"
    ...
    
    I hope this works for you, Thanks!
     
  4. xLeakDev Enzo

    xLeakDev Enzo Spider Jockey

    Messages:
    38
    GitHub:
    nya-enzo
    Yes, but your constant won't change values. And you can't redefine constants as they act like final static variables, for example
     
  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.