Dup Ver Goto

classes

pt2/lang/php 07-31 13:46:47
50 lines, 154 words, 1320 chars Monday 2023-07-31 13:46:47
class ClassName extends ParentClass {
  public static function GetMainInstance() { /* see below */ }
  public static $wibble = "boing";
  protected static $pt = null;  
}
$instance = ClassName::GetMainInstance()

Patterns

Singleton

Not exactly the Singleton pattern, but this is how you do a shared instance without having a global variable.

class ClassName extends ParentClass {
  public static function GetMainInstance() {
    if( is_null(ClassName::$pt) ) ClassName::$pt = new ClassName();
    return ClassName::$pt;
  }
  public static $wibble = "boing";
  protected static $pt = null;  
}
$instance = ClassName::GetMainInstance()

Superclasses

See this stackoverflow. Use parent rather than super.

class Foo {

  public function __construct($lol, $cat) {
    // Do stuff specific for Foo
  }

}

class Bar extends Foo {

  public function __construct()(
    parent::__construct("lol", "cat");
    // Do stuff specific for Bar
  }

}

Instantiate class named by string

See this stackoverflow

$className = 'MyClass';
$object = new $className;