SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2005
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question problem with using global variable in function

    Hi!

    I have problem with global variables.

    I have 3 files.:

    1. db_connection where I define variable $mdb2. I'm holding in $mdb2 the database connection.

    2. class file, where define the classes and their functions.
    in the beginning of file i'm making "require" to the first file.
    and using in declaration like this

    PHP Code:
    class class_name {
      function 
    blah() {
         
    globab $mdb2;
         .... 
    activity (db queriescalculations etc) ....

      }

    3. main fail. there are the communication with template and calling out the classes what i'm usin in 2nd file.


    The problem is, if i'm usin the second file directly then everything is working well. but if i'm using 3rd as it should be prober, then it is givin the error that cant make database query.
    i log in different places and found out that $mdb2 in function dont get the value. but it has values before calling that class in 3rd file and also when the second file is creating that class.

    I don't understand where the problems lies. because all files are "required". and should work.

    if i was including the first file into the function after global mdb2 then the sql queries did not fail.


    sorry my bad englsih, hope you understand and i'm waiting any help

  2. #2
    SitePoint Wizard Hammer65's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln Nebraska
    Posts
    1,161
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It may seem like more work to pass you database connection resource to classes that need it, though arguments, but that really is a far better way to do it. By using the "global" keyword, you are tying that class to a hard coded variable name in a separate scope and script.

    It is much better to pass that database connection through arguments to a class method (not necessarily the constructor). Do so by reference however, so that you aren't making copies of the db resource, but using the same one for all.

  3. #3
    SitePoint Enthusiast
    Join Date
    Sep 2005
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks for response. I changed the logic now and everything works.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •