Sai*_*han 3 php singleton static
我一直在PHP中使用Singleton类作为注册表对象.作为所有Singleton类,我认为main方法如下所示:
class registry
{
public static function singleton()
{
if( !isset( self::$instance ) )
{
self::$instance = new registry();
}
return self::$instance;
}
public function doSomething()
{
echo 'something';
}
}
Run Code Online (Sandbox Code Playgroud)
所以每当我需要一些注册表类时,我都会使用这样的函数:
registry::singleton()->doSomethine();
Run Code Online (Sandbox Code Playgroud)
现在我不明白创建一个普通的静态函数有什么区别.如果我只使用普通的静态类,它会创建一个新对象吗?
class registry
{
public static function doSomething()
{
echo 'something';
}
}
Run Code Online (Sandbox Code Playgroud)
现在我可以使用:
registry::doSomethine();
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释单例类的功能是什么.我真的不明白这一点.
静态函数是可以在不创建类的对象的情况下调用的函数.
registry::doSomething()
Run Code Online (Sandbox Code Playgroud)
Singleton是一种设计模式,应该防止类的用户创建多个类的实例.因此,通常只有一个单例类的实例.Singleton的构造函数应声明为private,并且具有提供单个实例对象的静态方法:
class Singleton
{
private Singleton()
{
}
private static var $instance = null;
public static getInstance()
{
if(self::$instance == null)
self::$instance = new Singleton();
return self::$instance;
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅http://en.wikipedia.org/wiki/Singleton_pattern
PS:抱歉我的PHP不好,语法可能不是100%正确,但你应该粗略地理解我在OOP方面的含义.