views:

135

answers:

2

Is it possible to create a connection in a PHP class file and use it in all of the different methods in the class? I am trying to open a connection in the constructor and i get an error when i get to the close connection method saying that the argument that I've provided in the mysql_close() statement isn't a valid MYSQL-Link souce.


Update: Ok I figured it out I had a variable misspelled.

+1  A: 

As long as the variable has the correct scope, it should work fine through the whole class. One way to do this would be to store the connection as a member variable, e.g.

$this->connection = mysql_connect(...);

This will make it visible to all class methods as long as you use the same method to retrieve it, e.g.

mysql_close($this->connection);
a_m0d
+2  A: 

It is entirely possible, you just need to make the database link a class member:

class MyDBClass {
    var $sth;

    function __construct($host, $user, $pass) {
        $this->sth = mysql_connect($host, $user, $pass);
    }

    function close() {
        mysql_close($this->sth);
    }
}
Paolo Bergantino
that is what I tried to do but I kept getting this: mysql_close(): supplied argument is not a valid MySQL-Link resource in /home/pilferingpanda/test.whysalltherumgone.com/pages/Tools/KickstartCreator/connection.php
TheGNUGuy
I just var_dumped it and it returned null, does the connection close after after a few seconds?
TheGNUGuy