phpscopesingleton-methods

Can clone object have same scope in singleton pattern?


In my case, I created a singleton object check below-

  class Foo {
     private static $obj = null;
     public static function create_obj () {
          if (self::$obj === null) {
               self::$obj = new self;
          }
         return self::$obj;
    }
  }

Then create object check below

$obj = Foo::create_obj();

Then clone $obj then

$obj1 = clone $obj;

Then $obj and $obj1 have difference scope why? And how to create only one object if clone then share same scope?


Solution

  • Then $obj and $obj1 have difference scope why?

    Because there is absolutely no reason for them to share the same "scope", if by that you mean be the same instance. You implemented that singleton using the method you did, but that have no effect on the rest of the behaviour of PHP. The clone construct does not use your create_obj() method, so it will not be a singleton.

    And how to create only one object if clone then share same scope?

    By not using clone. If you want your class to be a singleton with this method, you need to always use your singleton creation method.


    That is hard to tell from just that, but it seems you are having contradictory goals here. If you need two different instances of an object but representing the same instance, simply use the same instance of the object. There is virtually no difference.

    If you need a single instance of an object to be used throughout a whole script execution, no need for a singleton, simply instantiate it once, then pass it to every other object that needs it. Objects are passed in a reference-like way in PHP, which means that if you pass it to different functions, all functions will be acting on the same instance.