【发布时间】:2010-04-28 18:30:10
【问题描述】:
我将如何使用最初加载到整个网站的对象实例?
我希望在任何地方都可以使用 $myinstance。
$myinstance = new TestClass();
谢谢!
【问题讨论】:
-
您想要每一代页面都有一个实例,还是想要每个生成的页面都可以使用相同的实例?
我将如何使用最初加载到整个网站的对象实例?
我希望在任何地方都可以使用 $myinstance。
$myinstance = new TestClass();
谢谢!
【问题讨论】:
您要查找的内容称为singleton pattern.
如果你深入 OOP 架构,并且想在未来做单元测试之类的事情:单例被认为是一种不完美的方法,而不是 OOP 意义上的“纯粹”。我曾就这个问题向a question 询问过一次,并在使用其他更好的模式时得到了很好的结果。很多很好的阅读。
如果您只是想开始做某事,并且需要随处可用的 DB 类,只需使用 Singleton。
【讨论】:
您只需要在全局范围内声明变量(例如,在整个代码的开头),当您想在函数中使用它时,请使用“全局”语句。见http://php.net/global。
【讨论】:
我不能 100% 确定我得到了你想要做什么......但无论如何我都会尝试回答。
我认为您可以将其保存到会话变量中,使用序列化/反序列化函数来保存/检索您的类实例。可能您会将 TestClass 编码为单例,但这实际上取决于您要执行的操作。
例如:
if (!isset($_SESSION["my_class_session_var"])) // The user is visiting for the 1st time
{
$test = new TestClass();
// Do whatever you need to initialise $test...
$_SESSION["my_class_session_var"] = serialize($test);
}
else // Session variable already set. Retrieve it
{
$test = unserialize($_SESSION['my_class_session_var']);
}
【讨论】:
有一种设计模式叫做 Singleton。简而言之:
把 __construct 和 __clone 改成私有的,所以调用 new TestClass() 会报错!
现在创建一个类,该类将创建对象的新实例或返回现有对象...
例子:
abstract class Singleton
{
final private function __construct()
{
if(isset(static::$instance)) {
throw new Exception(get_called_class()." already exists.");
}
}
final private function __clone()
{
throw new Exception(get_called_class()." cannot be cloned.");
}
final public static function instance()
{
return isset(static::$instance) ? static::$instance : static::$instance = new static;
}
}
然后尝试扩展这个类并定义静态 $instance 变量
class TestClass extends Singleton
{
static protected $instance;
// ...
}
现在试试这个:
echo get_class($myinstance = TestClass::instance();
echo get_class($mysecondinstance = TestClass::instance());
完成
【讨论】: