Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 26th, 2012  |  syntax: None  |  size: 1.04 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Is it possible to get the current class instance from a static class method?
  2. class C{
  3.  
  4.   function static getInstance(){
  5.     // here
  6.   }
  7.  
  8. }
  9.  
  10.  
  11. $c = new c;
  12. print_r(C::getInstance()); // should be $c
  13.        
  14. print_r($c::getInstance()); // should be $c
  15.        
  16. class C {
  17.  
  18.   private static $instance;
  19.  
  20.   public static function getInstance(){
  21.     return self::$instance;
  22.   }
  23.  
  24.   public function __construct() {
  25.     self::$instance = $this;
  26.   }
  27. }
  28.  
  29. $c = new c;
  30. print_r(C::getInstance()); // should be $c
  31.        
  32. class C
  33. {
  34.    private static $instance;
  35.  
  36.    public static function getInstance()
  37.    {
  38.      if (!is_null(self::$instance)) return self::$instance;
  39.      self::$instance = new self;
  40.      return self::$instance;
  41.    }
  42.  
  43.    private function __construct()
  44.    {
  45.      // Whatever
  46.    }
  47. }
  48.  
  49. $c = new C; // This will not work since __construct() is private
  50. $c1 = C::getInstance();
  51. $c2 = C::getInstance();
  52.  
  53. echo ($c1 == $c2 ? 'yes' : 'no'); // yes
  54.        
  55. <?php
  56. class CallableClass
  57. {
  58.     public function __invoke()
  59.     {
  60.         return this;
  61.     }
  62. }
  63. $obj = new CallableClass;
  64. var_dump($obj);