SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2001
    Posts
    84
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    how to get a handle on $DB connection object inside a different function?

    I declare this on the main page:

    $db =& DB::connect('mysql://namew@localhost/db');

    Then I want to use $DB in a function without declaring it again inside the function.

    function getthisfield($fldName) {
    $res =& $db->query('whatever');
    .....
    }

    I have seen someone use something like this:

    function getthisfield($fldName) {
    global $db;
    $res =& $db->query('whatever');
    .....
    }

    But I can't get that to work.

    Do I need to declare it a global before going in the function? Do I need to pass it as a parametere? If so, how?

    Any ideas/thoughts are appreciated!
    signature

  2. #2
    SitePoint Addict Fire59's Avatar
    Join Date
    Aug 2003
    Location
    mn
    Posts
    272
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you should be able to use global or else pass it by ref.

    PHP Code:
    function getthisfield($fldName,&$db) {
    $res $db->query('whatever');
    .....
    }

    $db =& DB::connect('mysql://namew@localhost/db');
    getthisfield($fieldname,$db); 

  3. #3
    Non-Member coo_t2's Avatar
    Join Date
    Feb 2003
    Location
    Dog Street
    Posts
    1,819
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    You should pass things into functions whenever you can, as opposed to using "global". You should strive to make functions tiny little bits of self-contained code. Look at the function's argument/parameter list as its interface to the outside world.
    And try to keep the use of global variables, in general, down to a minimum.

    --ed

  4. #4
    SitePoint Enthusiast
    Join Date
    Sep 2001
    Posts
    84
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I used the code example from fire59 and it worked great - thanks!
    signature


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
  •