Q:

Use of included class in another class

I'm trying to use a database class (ADOdb for PHP) but I don't know how to use it in another class.
Example:
<?php
include_once("adodb.inc.php");
$conn = NewADOConnection('mysql');

class Contacts {
    public function getData(){
        $conn->Connect(...);
        //do something
    }
}
?>

I think the problem is that I can not call $conn because its defined outside the class.
Notice: Undefined variable: conn
Fatal error: Call to a member function Connect() on a non-object
Maybe I'm doing it the wrong way, but I really don't know how to fix this.  
Can somebody please help me out? Thanks a lot!

A:

You have a number of choices:
Use the global reserve word:
<?php
include_once("adodb.inc.php");
$conn = NewADOConnection('mysql');

class Contacts {
    public function getData(){
        global $conn;
        $conn->Connect(...);
        //do something
    }
}
?>

Or pass $conn to your object on creation
$contacts = new Contacts($conn);

class Contacts {
    protected $conn;
    public function __construct($conn){
        $this->conn = $conn;
    }
    public function getData(){
        $this->conn->Connect(...);
        //do something
    }
}
?>

Or you could yous a Singleton data connection object. But that is considered a anti-pattern so I would inject your dependency as in option 2.

A:

Why not simply do like this ?!
<?php
include_once("adodb.inc.php");
$conn = NewADOConnection('mysql');

$conn->Connect(...);

class Contacts {

    protected $_connection;

    public function __construct($conn)
    {
        $this->_connection = $conn;
    }
    public function getData(){

        //do something

    }
}

$contacts = new Contacts($conn);

$foobar = new FooBar($conn);

?>

It makes sense to establish connection outside the class, and then pass in already workable object. And of-course to share the same connection object among all the classes which require it.
P.S i would really reallly recommend to drop ADODB and start learning PDO.

