Reputation: 12740
I've created Singleton class below but how do I know that only one instance has been created. How do I test it? Also, is there any difference between self::$instance = new FileProcessor()
and self::$instance = new static()
or which one should I use?
Thanks
CLASS
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);
OUTPUT
FileProcessor Object
(
)
FileProcessor Object
(
)
Upvotes: 0
Views: 205
Reputation: 870
You can compare the result by using ===
operator. In your case:
$obj_1 === $obj_2
will return true
if both objects refer to the same instance. More info here: http://www.php.net/manual/en/language.oop5.object-comparison.php. And also here is a good explanation of using new static()
: New self vs. new static
Upvotes: 1
Reputation: 522372
Ideally you wouldn't be using a singleton pattern to begin with. Instead you dependency inject an instance of FileProcessor
to everything that needs it. That means all the places in your app which need FileProcessor
don't "get it themselves", rather they receive it from a higher authority. Instead of:
function foo() {
$fp = FileProcessor::getInstance();
...
}
you do:
function foo(FileProcessor $fp) {
...
}
This allows you to instantiate exactly one FileProcessor
and inject it everywhere it's needed. This gives you full control over its use. You can couple this with a registry/dependency injection container pattern to make managing dependencies easier.
Upvotes: 2
Reputation: 392
var_dump function allows you to view the contents of the object. This code demonstrates that the objects are really the same:
<?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);
Upvotes: 1