Improve performance by reusing PHP objects

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.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.