Home » Php » php – Can not assign value to static variable inside class

php – Can not assign value to static variable inside class

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to implement singleton pattern for a class. I have a static variable $classInstance and when assigning class object getting the error “Parse error: syntax error, unexpected ‘='”.

  /**
   * Hold instance of class.
   */
  private static $classInstance = null;

  /**
   * Create the client connection.
   */
  public static function createClient() {
    if (self::classInstance === null) {
      self::classInstance = new self(); // Getting error on this line.
    }
    return self::classInstance;
  }
How to&Answers:

The error was because of missing “$” while accessing static property of class with self keyword.

  /**
   * Create the client connection.
   */
  public static function createClient() {
    if (self::$classInstance === null) {
      self::$classInstance = new self(); // Note the $ sign.
    }
    return self::$classInstance;
  }