单例类范围问题 [英] Singleton class scope problem
问题描述
在我的网站上,我想制作两个课程。可以实例化的一个
正常和一个具有扩展功能的一个只能实例化一次的
。因此,Singleton模式似乎是第二类的逻辑
选择。但是,我希望第二个
(单例)类扩展第一个。这样的事情:
<?php
class User
{
public function __construct()
{
doSomething();
}
}
class会员扩展用户
{
private static $ instance = NULL;
公共静态函数getInstance()
{
if(self :: $ instance === NULL)
self :: $ instance = new Member;
return self :: $实例;
}
私函数__construct(){}
私函数__clone(){}
}
?>
但这会给我以下错误:
致命错误:成员:: __构造的访问级别( )必须在第6行的class.member.php中公开(在类User中为
)
但我不希望构造函数成为公开,因为我希望它不会创建多个实例。
有人知道怎么办吗?
谢谢。
On my site I want to make two classes. One that can be instantiated
normally and one with extended functionality that can only be
instantiated once. The Singleton pattern thus seems like a logical
choice for the second class. However, I would like the second
(singleton) class to extend the first. Something like this:
<?php
class User
{
public function __construct ()
{
doSomething();
}
}
class Member extends User
{
private static $instance = NULL;
public static function getInstance ()
{
if (self::$instance === NULL)
self::$instance = new Member;
return self::$instance;
}
private function __construct () {}
private function __clone () {}
}
?>
But this gives me the following error:
Fatal error: Access level to Member::__construct() must be public (as
in class User) in class.member.php on line 6
But I don''t want the constructor to be public, because I want it to be
impossible to create more than one instance.
Does anybody know what to do about this?
Thanks.
推荐答案
instance = NULL;
public静态函数getInstance()
{
if(self ::
instance = NULL;
public static function getInstance ()
{
if (self::
instance === NULL)
self ::
instance === NULL)
self::
instance = new Member;
return self ::
instance = new Member;
return self::
这篇关于单例类范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!