13 line singleton implementation
class Singleton {
private static $instance = null;
private function __construct(){
//do something
}
public static function getInstance(){
self::$instance !== null ?: self::$instance = new self();
return self::$instance;
}
}Written by Marco Bunge
Related protips
1 Response
It's important to note that this isn't thread safe. This is something similar I always use...it's in c# though, but the idea is the same http://snippetrepo.com/snippets/the-mingleton-a-singleton-that-plays-nice. It's been awhile since I've dug around in php so I don't remember off the top of my head how to lock, but if you can implement it like I did in mine you'd have a pretty good baseline.
The reason this is important is because you plan on using this in a static/global scope, and it's possible for two things to call getInstance right now and create two separate self() objects.
Anyways, good stuff.
Have a fresh tip? Share with Coderwall community!
PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.
Security insights from Cside