CodeIgniter Forums
Database connection in static method - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: General Help (https://forum.codeigniter.com/forum-24.html)
+--- Thread: Database connection in static method (/thread-76847.html)



Database connection in static method - Cyto5 - 06-26-2020

In CI4, how would you create a static variable holding the $db connection to use inside of static methods? Everything I have tried either brings it only as a non-static var or doesn't seem to work. I even tried Manual Model Creation but was unable to get that to work either.

Thanks[url=https://codeigniter.com/user_guide/models/model.html#id22][/url]


RE: Database connection in static method - Cyto5 - 06-27-2020

So far the best solution I could find is: https://stackoverflow.com/questions/3312806/static-class-initializer-in-php/3312881#3312881


PHP Code:
// file Foo.php
class Foo
{
  protected static $db;
  static function init() { if(empty(self::$db)) self::$db =  db_connect(); }
}

Foo::init(); 

Basically if the file is called it will call init and init will setup the static database and if it's called again it will just skip that setup line. Now I can access self::db from within my classes static methods. I found out constructors don't get called when accessing a method statically which is why a bunch of my previous "tests" we not working including following Manual Model Creation steps. If there is a better way to handle this let me know but this seems to work for now. Now I can use "self::$db" inside a static method.