user2118534
user2118534

Reputation: 17

call a class in another class

Hi I have some problem to call a class in another class, below code the 1 is ok to show result, but in 2 use the same code add to another class, I don't know why it is not work.
Thanks.

1

require 'database.php';
$database = new Database();

$database->query('SELECT user_id, user_email FROM tb WHERE user_id = :user_id');
$database->bind(':user_id', '1');
$rows = $database->resultset(); // fetchall

echo "<pre>";
print_r($rows);
echo "</pre>";

2

require 'database.php';
$database = new Database();

class test{
    public function testf(){
        print"log";
        $database->query('SELECT user_id, user_email FROM tb WHERE user_id = :user_id');
        $database->bind(':user_id', '1');
        $rows = $database->resultset(); // fetchall

        echo "<pre>";
        print_r($rows);
        echo "</pre>";
        print"log";
    }
}
$foo = new test();
$foo -> testf();

Upvotes: 0

Views: 71

Answers (2)

MIIB
MIIB

Reputation: 1849

Try this:

    require 'database.php';


    class test{
var $database;
public function test(){
$database = new Database();
}
        public function testf(){
            print"log";
            $this->database->query('SELECT user_id, user_email FROM tb WHERE user_id = :user_id');
            $this->database->bind(':user_id', '1');
            $rows = $database->resultset(); // fetchall

            echo "<pre>";
            print_r($rows);
            echo "</pre>";
            print"log";
        }
    }
    $foo = new test();
    $foo -> testf();

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

Note that $database is available only in the global scope - not in the scope of test. Change it to:

require 'database.php';
$database = new Database();

class test{
    public function testf($database){
        print"log";
        $database->query('SELECT user_id, user_email FROM tb WHERE user_id = :user_id');
        $database->bind(':user_id', '1');
        $rows = $database->resultset(); // fetchall

        echo "<pre>";
        print_r($rows);
        echo "</pre>";
        print"log";
    }
}

$foo = new test();
$foo -> testf($database);

Another option is to have $database as a class variable (sounds better). Then do this:

class test {

    protected $database; 

    public function __construct() {
        $this->database = new Database();
    }


    public function testf(){
        print"log";
        $this->database->query('SELECT user_id, user_email FROM tb WHERE user_id = :user_id');
        $this->database->bind(':user_id', '1');
        $rows = $this->database->resultset(); // fetchall

        echo "<pre>";
        print_r($rows);
        echo "</pre>";
        print"log";
    }   

}

$foo = new test();
$foo -> testf();

Upvotes: 1

Related Questions