27
Jun '12

Static Instances in PHP

When pulling apart other people’s code, all too often I come across occasions where people are using up resources creating loads of instances of objects where one would do just as well. So here is the quickest way to use static object instances that can be accessed from anywhere (apologies if I’m teaching anyone to suck eggs).

class MyClass {

	protected static $instance;

	protected function __construct() {
	}

	public static function getInstance() {
		if(!self::$instance)
			self::$instance = new self();

		return self::$instance;
	}
}

And there you have it! Just call it like so and you never need to spank your resources in such a manner again!

$instance = MyClass::getInstance();

Leave a Reply