1

Say I have a case where I need a helper class that should have static methods, but those methods need a static object to manipulate.

I would rather have the helper be self-contained, so I only have to include the file. Alternatively, one could add the initialization call to some kind of autoloader, but I would rather avoid that.

Considering that you can't use a __construct method here because the class is never instantiated, is this an acceptable alternative?

class HelperClass
{
  private static $property;
  private static function init()
  {
    if (!isset(self::$property))
      self::$property = new stdClass;
  }
  static function addSomething($key, $value)
  {
    self::$property->$key = $value;
  }
  static function getObject()
  {
    if (isset(self::$property))
      return self::$property;
    else
      return new stdClass;
  }
}
Allenph
  • 1,875
  • 27
  • 46
  • 1
    I'm not sure why you make a class with only static methods when you need an object anyway... – Charlotte Dunois Dec 22 '16 at 18:34
  • Well, at first this particular class was a trait, but it should be more of a service. The class has a bunch of static methods which build a JSON object in a standardized pattern for error reporting back to the client app. I don't want to instantiate this object over and over, I just want one central one with a global array of setters and getters. – Allenph Dec 22 '16 at 18:41
  • You might wanna use Singleton Pattern then... https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5 – Charlotte Dunois Dec 22 '16 at 18:43
  • I've looked at using a singleton...this seems preferable, but if there's something WRONG with this way, then yes, I'll probably use a singleton. – Allenph Dec 22 '16 at 18:49

0 Answers0