PHP中的单实例对象(下)

最后一个问题是确保用户只能创建一个实例。实现的方法是,在类中创建一个static成员变量,并且让getInstance方法检查这个变量是否已经设置了。如果还未设置,那么这个方法创建对象实例并且将实例赋给这个static成员变量。然后,方法返回存储的实例,如下所示:

<?php

class OnlyNeedOne
{
//
//holds the single instance of this class
//
private static $s_instance;

private function __construct()
{
}

public static function getInstance()
{
if(self::$s_instance === NULL)
{
self::$s_instance = new OnlyNeedOne();
}
return self::$s_instance;
}
}

//
//create new instance and assigns it to $one
//
$one = OnlyNeedOne::getInstance();

?>

相关文章: 

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)