PHP constructors and static functions

后端 未结 4 1298
野性不改
野性不改 2021-02-12 20:06

I\'m a bit confused on how constructors work in PHP.

I have a class with a constructor which gets called when I instantiate a new object.

$foo = new Foo(         


        
4条回答
  •  Happy的楠姐
    2021-02-12 20:39

    Assumption PHP 5.x

    Different goals, different path

    1. create a new instance of a class (object)

      class myClassA
      {
         public $lv;
      
         public function __construct($par)
         {
             echo "Inside the constructor\n";
             $this->lv = $par;
         }
      }
      
      $a = new myClassA(11);
      $b = new myClassA(63);
      

      because we create a new object PHP calls:

      __construct($par);

      of the new object, so:

      $a->lv == 11 
      
      $b->lv == 63
      
    2. use a function of a class

      class myClassB
      {
          public static $sv;
      
          public static function psf($par)
          {
              self::$sv = $par;
          }
      }
      
      myClassB::psf("Hello!");
      $rf = &myClassB::$sv;
      myClassB::psf("Hi.");
      

      now $rf == "Hi."

      function or variabiles must defined static to be accessed by ::, no object is created calling "psf", the "class variable" sv has only 1 instance inside the class.

    3. use a singleton created by a Factory (myClassA is above)

      class myClassC
      {
      
          private static $singleton;
      
          public static function getInstance($par){
      
              if(is_null(self::$singleton)){
      
                  self::$singleton = new myClassA($par);
      
              }
      
              return self::$singleton;
      
          }
      
      }
      
      $g = myClassC::getInstance("gino");
      echo "got G\n";
      
      $p = myClassC::getInstance("pino");
      echo "got P\n";
      

    Using the factory (getInstance) the first time we construct a new object having $par set to gino.

    Using the factory the second time $singleton has already a value that we return. No new object is created (no __construct is called, less memory & cpu is used).

    The value of course is an object instanceOf myClassA and don't forget:

    myClassC::$singleton->lv == "gino"

    Pay attention to singletons:

    What is so bad about singletons?

    http://www.youtube.com/watch?v=-FRm3VPhseI

    By my answer I don't want promote/demote singleton. Simply from the words in the question, I made this calc:

    "static"+"__construct"="singleton"!

提交回复
热议问题