is it possible t开发者_高级运维o create a singleton class in PHP 4?
Right now I have something like http://pastebin.com/4AgZhgAA which doesn't even get parsed in PHP 4
What's the minimum PHP version required to use a singleton like that?
PHP4 and OOP === car without engine (:
It is possible but impractical.
Look this sample code:
class SomeClass
{
var $var1;
function SomeClass()
{
// whatever you want here
}
/* singleton */
function &getInstance()
{
static $obj;
if(!$obj) {
$obj = new SomeClass;
}
return $obj;
}
}
Alex, this article should be helpful - http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-i/ . The key is to use a base class, and in the child class constructor, invoke the parent's singleton instantiation method.
You could also use a wrapper function like so;
function getDB() {
static $db;
if($db===NULL) $db = new db();
return $db;
}
When you programming in a language which is not strict OOP, it's easy to use the dark side of the force:
function getInstance() {
global $singleObj;
if (!is_object($singleObj)) $singleObj = new Foo();
return $singleObj;
}
And why not? Looks uglier than a strict singleton? I don't think so.
(Also, don't forget that PHP4 don't support inheritance - I've spent some hours with it.)
精彩评论