0

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.

9
  • 4
    Class vars defined there must be constant expressions. Try assigning it in the function. Commented May 13, 2015 at 20:37
  • I need the variable to be defined outside the doSomeStuff function so I can use it in several other functions. Thanks Commented May 13, 2015 at 20:38
  • Well, you can't do it there. Commented May 13, 2015 at 20:39
  • 1
    Typo. You call doSomeStuff but in the class the name is doSomStuff. Commented May 13, 2015 at 20:40
  • Edited, please other suggestions? Commented May 13, 2015 at 20:41

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.