我在下面创建了Singleton类,但是我怎么知道只创建了一个实例。我该如何测试?另外,self::$instance = new FileProcessor()
和self::$instance = new static()
之间是否存在差异,或者我应该使用哪一种?
由于
类
class FileProcessor
{
protected static $instance = null;
public static function get_instance()
{
if (self::$instance === null)
{
self::$instance = new FileProcessor();
//self::$instance = new static();
}
return self::$instance;
}
}
$obj_1 = FileProcessor::get_instance();
echo '<pre>'; print_r($obj_1);
$obj_2 = FileProcessor::get_instance();
echo '<pre>'; print_r($obj_2);
输出
FileProcessor Object
(
)
FileProcessor Object
(
)
答案 0 :(得分:2)
理想情况下,您不会开始使用单例模式。相反,您依赖注入 FileProcessor
的实例到需要它的所有内容。这意味着您的应用中需要FileProcessor
的所有地点都不会自己获取#34;而是他们从更高级别的权限接收。而不是:
function foo() {
$fp = FileProcessor::getInstance();
...
}
你这样做:
function foo(FileProcessor $fp) {
...
}
这允许您实例化一个FileProcessor
并将其注入所需的任何地方。这使您可以完全控制其使用。您可以将其与注册表/依赖项注入容器模式结合使用,以便更轻松地管理依赖项。
答案 1 :(得分:1)
您可以使用===
运算符比较结果。在你的情况下:
如果两个对象都引用同一个实例,$obj_1 === $obj_2
将返回true
。更多信息:http://www.php.net/manual/en/language.oop5.object-comparison.php。此处也是使用new static()
:New self vs. new static
答案 2 :(得分:1)
var_dump函数允许您查看对象的内容。 此代码演示了对象实际上是相同的:
<?php
class FileProcessor
{
protected static $instance = null;
private $arr = array();
public static function get_instance()
{
if (self::$instance === null)
{
self::$instance = new FileProcessor();
//self::$instance = new static();
}
return self::$instance;
}
public function set($key, $value)
{
$this->arr[$key] = $value;
}
}
$obj_1 = FileProcessor::get_instance();
$obj_1->set('this-is-key', 'this-is-value');
echo '<pre>'; var_dump($obj_1);
$obj_2 = FileProcessor::get_instance();
echo '<pre>'; var_dump($obj_2);