I’ve been doing a ton of optimizations on one of my main sites and one thing that I’ve been doing more and more is trying to reuse objects whenever possible. What’s this entail? All it takes is creating a static function to return an instance of the object instead of instantiating a new one each time:

class Object
{
	private static $instance = null;

	private function __construct()
	{
		// Not necessary, but making this private will block all public instantiations
	}

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

	public function doSomething()
	{
		// Does something...
	}
}

Instead of doing $object = new Object() you’d simply do $object = Object::getInstance() and would be able to interact with the object just like it was instantiated.

If you’re only using an object once on a page, this isn’t really necessary but I’ve found that as the complexity of my site grew and I needed objects in multiple places I was instantiating the same classes a ton! Reusing the object in this way is significantly easier than passing around objects all over your code and you can easily swap the instantiation code for the get instance code without any additional rework.





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: