self points to the class in which it is written. So, if your getInstance method is in a class name MyClass, the following line : self::$_instance = new self(); Will do the same as : self::$_instance = new MyClass(); Edit : a couple more informations,

after the comments. If you have two classes that extend each other, you have two situations : getInstance is defined in the child class getInstance is defined in the parent class The first situation would look like this (I've removed all non-necessary co

de, for this example -- you'll have to add it back to get the singleton behavior)* :

 

   1: class MyParentClass { }
   2:  
   3: class MyChildClass extends MyParentClass {
   4:  
   5:      public static function getInstance() { return new self(); }
   6:  
   7: }
   8:  
   9: $a = MyChildClass::getInstance();
  10:  
  11:  var_dump($a);

Here, you'll get : object(MyChildClass)#1 (0) { } Which means self means MyChildClass -- i.e. the class in which it is written.

For the second situation, the code would look like this :

 

   1: class MyParentClass {
   2:  
   3:     public static function getInstance() { return new self(); }
   4:  
   5:  }
   6:  
   7: class MyChildClass extends MyParentClass { }
   8:  
   9: $a = MyChildClass::getInstance();
  10:  
  11: var_dump($a);
  12:  

And you'd get this kind of output : object(MyParentClass)#1 (0) { } Which means self means MyParentClass -- i.e. here too, the class in which it is written.

With PHP < 5.3, that "the class in which it is written" is important -- and can sometimes cause problems. That's why PHP 5.3 introduces a new usage for the static keyword : it can now be used exactly where we used self in those examples :

 

   1: class MyParentClass {
   2:  
   3:     public static function getInstance() { return new static(); }
   4:  
   5: }
   6:  
   7: class MyChildClass extends MyParentClass { }
   8:  
   9: $a = MyChildClass::getInstance();
  10:  
  11: var_dump($a);

But, with static instead of self, you'll now get : object(MyChildClass)#1 (0) { } Which means that static sort of points to the class that is used (we used MyChildClass::getInstance()), and not the one in which it is written. Of course, the behavior of self

has not been changed, to not break existing applications -- PHP 5.3 just added a new behavior, recycling the static keyword. And, speaking about PHP 5.3, you might want to take a look at the Late Static Bindings page of the PHP manual.

posted on 2013-12-31 15:16  doop-ymc  阅读(390)  评论(0编辑  收藏  举报