oop - PHP: How to pass existing database connection to static class methods? -


I have a set of static class methods. I have an existing database connection in the object variable $ DB stored in the script. How can I call those static class methods and use them to use that Debian object every time it passed as a parameter on class method?

For example, I unfortunately use a global now:

  square fu {public static function bar () {global $ db; Return $ DB-> DSN_STRING; }}  

It seems that I need to have my static class to call themselves regularly, in any way, $ DB connections without having it restored. Note: I can not inject it into static classes because it is not interactive.

Of course, the problem is solved if I switch from a stable class to regular class and instantiate my $ Foo object then I can inject $ DB var as a setting on the public variable To get a $ DB var or add a public law and then set the Private World of $ Foo Object or, accept a class constructor $ DB Var and set the Private World of $ Foo Object. But all three techniques require that I switch from a steady class to regular class.

Some people have such a register pattern or a singleton pattern (I think this is the same thing? Do I need to solve this problem efficiently?

Most The thing is that I want to avoid "global $ db" because people get distracted about it.

I will use singleton pattern for this, and I'll use one square that I have a cave here Database_Manager will call:

  class Database_Manager {Private static $ example; personal $ db_connection; public stable work getInstance () {if (self: $ example == zero) {$ className = __CLASS__ ; Self :: $ instance = new $ className ();} return self :: $ example;} public static work initializeConnection ($ connectionInfo) {$ db = self :: getInstance (); // call init functions .. db Connect, etc. Save $ db-> db_connection connection;} Public stable work getDb () {$ db = self :: getInstance (); Return $ db- & gt; db_connection; }}  

You can set things once with the initial connection () call, and then just call database_Manager :: getDb ().

Good thing about this approach is that it is easily modified to manage connections for many databases, and you are guaranteed an open connection only for one copy database.

Note that I have some knight-write singleton implementation, such as __ composition () function declaring personal (most of the above is copied from memory). I wanted to show the whole perspective.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

jquery - SimpleModal Confirm fails to submit form -

php - Multiple Select with Explode: only returns the word "Array" -