How do I make up for the lack of static initializers in PHP?

I am going to put each class in a separate file and do static initialization outside the class definition.

The problem is that initialization will happen before this class is really needed (this will happen when the file containing this class is included for the first time). This is a problem because it may happen that the class will not be used at all, so initialization is not needed. And I believe that the practice of including the files used is not at the beginning of your code - it's just a dirty technique.

If anyone has a viable solution to this problem, I would really appreciate it.

+3
source share
5 answers

You can search for __autoload when a class is not found, it is called and should include a file containing this class. You can put static initializers in this function.

+2
source

Take a look at this code. It uses an instance of a singleton database, but you can still instantiate the class:

class DB
{
    private static $_db;

    public static function pdo()
    {
        if (is_null(self::$_db))
        {
            self::$_db=new PDO('pgsql:host=localhost;
                                port=5432;
                                dbname=testdb;
                                user=postgres;
                                password=abc123');
            self::$_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        return self::$_db;
    }

public static function factory()
{
    return new self;
}

private function __construct() {}

If you need a DB instance, you do DB::factory(). DB uses self::pdo()to return singleton to access the database.

+3
source

- ... ... ... , ... , ... , __get __set magic... , ... ...

Hi.php:

class Hi{
public static $v = "0";
}

Hi::$v= "2";
// end of Hi.php file

just use the .php file for each class ... and do static initialization outside the class definition ...

+3
source

Use a single template instead of static calls:

<?php
class Foo {

   protected static $_instance;

   /**
   * @return Foo
   */
   public static function getInstance() {
        return (null === self::$_instance)? 
            self::$_instance :
            self::$_instance = new Foo();
   }

   protected function __construct() {
        // initialize here
   }
}
0
source

So I do it. The only cost is testing the static member $ doneinit every time it is created.

class Foo {
   private static $doneinit=false;

   private static init() {
      // do static initialisation here

      self::$doneinit=true;
   }

   public function __construct() {
      if (!self::$doneinit) self::init();

      // go on to do the rest of construction
   }
}

Simple and it keeps everything inside the class.

0
source

Source: https://habr.com/ru/post/1717746/


All Articles