Skip to main content
2 of 2
Added pure-static calls and explanation of the code
jhilgeman
  • 231
  • 1
  • 4

Looks sort of like you're trying to accomplish a singleton pattern, using the App class to control them all. Try this approach instead:

<?php
// Base / abstract class that defines a basic singleton pattern
abstract class SingletonProvider
{
  // Singleton pattern
  protected static $_instance;  
  public static function getInstance()
  {
    if(static::$_instance == null)
    {
      static::$_instance = new static();
    }
    return static::$_instance;
  }

  // Private constructor
  private function __construct() { }
}


// A specific provider class definition that inherits the singleton pattern
class MyProvider extends SingletonProvider
{
  // Class-specific instance reference
  protected static $_instance;  

  // --- CLASS INSTANCE-SPECIFIC PROPERTIES AND METHODS BELOW HERE ---

  // Class properties
  public $FieldX;
  
  protected function __construct()
  {
    $this->FieldX = "Hello World!";
  }
}


// Another specific provider class definition that inherits the singleton pattern
class MyOtherProvider extends SingletonProvider
{
  // Class-specific instance reference
  protected static $_instance;  

  // --- CLASS INSTANCE-SPECIFIC PROPERTIES AND METHODS BELOW HERE ---
  
  // Class properties
  public $FieldY;
  
  protected function __construct()
  {
    $this->FieldY = "Foo";
  }

  public function MakeMoreExciting($sentence)
  {
    return $sentence . "!!!!!!!!";
  }
}


// Usage examples
echo MyProvider::getInstance()->FieldX; // Hello World!
echo MyOtherProvider::getInstance()->FieldY; // Foo
echo MyOtherProvider::getInstance()->MakeMoreExciting("Hi there"); // Hi there!!!!!!!!

The "static" keyword is used for late static binding, which basically means that when you run MyOtherProvider::getInstance(), all the "static" references like "static::$_instance" resolve to the calling class, so it's like automatically determining either MyOtherProvider::$_instance or MyProvider::$_instance, depending on which class is being called.

The protected static $_instance is there to ensure that each class has its own property to hold the class instance.

In theory, you could even shorten all of this up into nothing but static methods and properties, too:

abstract class MyOtherProvider
{
  // Class properties
  public static $FieldY;
  
  public static function MakeMoreExciting($sentence)
  {
    return $sentence . "!!!!!!";
  }
}

echo MyOtherProvider::MakeMoreExciting("Hi there"); // Hi there!!!!!!

Although sometimes you might want an actual instance rather than just being completely static.

jhilgeman
  • 231
  • 1
  • 4