Skip to content

Instantly share code, notes, and snippets.

@nathanielks
Created December 30, 2013 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanielks/8190042 to your computer and use it in GitHub Desktop.
Save nathanielks/8190042 to your computer and use it in GitHub Desktop.
Instead of having to add the get_instance function to every class you want to use, I wanted to be able to extend an abstract class with just that functionality. This is the fruit of my efforts. You can read up more on it here:http://us1.php.net/lsb and here:
<?php
abstract class Cur_Abstract {
public static $instance;
public static function get_instance() {
// Instead of doing is_object( static::$instance ), we check to see if
// static::$instance is an instance of static::$class. Because we're
// extending the class, static::$instance wants to be shared across any
// classes that extend Cur_Abstract, muddling up this check. If it were
// just is_object, it would pass, even though the instance is an
// instance of another class.
if ( ! ( static::$instance instanceof static ) ) {
// This is where some of the magic is able to happen. Using Late Static
// Binding, we're able to refer to the extending class ( static ), rather than the
// class being extended. In this case, static will be Cur_SomeClass when
// it's being instantiated later on down the line.
static::$instance = new static();
}
return static::$instance;
}
}
<?php
include_once 'class-cur-abstract.php';
class Cur_SomeClass extends Cur_Abstract {
}
$someclass = Cur_SomeClass::get_instance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment