在另一个类中调用一个类

时间:2013-02-28 07:12:52

标签: php

嗨我在另一个类中调用一个类有一些问题,在代码下面1可以显示结果,但在2中使用相同的代码添加到另一个类,我不知道为什么它不起作用。<登记/> 感谢。

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();

2 个答案:

答案 0 :(得分:1)

请注意,$database仅在全局范围内可用 - 不在test的范围内。将其更改为:

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);

另一个选择是将$ database作为类变量(听起来更好)。然后这样做:

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();

答案 1 :(得分:0)

试试这个:

    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();