简体   繁体   中英

PHP static variable as a result of another function

I am trying to define a PHP class with some static variables. I am trying to do the following to avoid using globals.

class class_Name{
  private static $var1 = is_plugin_inactive('plugin/plugin.php'); //check if WordPress has this plugin active
  public static function doSomeStuff(){
    echo $var1;
  }
}
//init class
class_Name::doSomeStuff();

This always get's me an error Parse error: syntax error, unexpected '(', expecting ',' or ';' in my_file.php at line where I am defining the static variable.

Any help please.

if you like to save a non constant expression in $var1 you need to set in from a method, for example an init method:

class class_Name {

    private static $var1 = null;

    public static function init() {
        self::$var1 = is_plugin_inactive('plugin/plugin.php');
    }

    public static function doSomeStuff() {
        echo self::$var1;
    }

}

class_Name::init();

class_Name::doSomeStuff();

Not sure of your exact situation, but can you do:

class class_Name {
    private static $var1 = null;   

    //check if WordPress has this plugin active
    public static function doSomeStuff(){
        if(is_null(self::$var1))
            self::$var1 = is_plugin_inactive('plugin/plugin.php');
        echo self::$var1;
    }
}

Basically call the function like you are wanting to, but initialize it if its not already?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM