0

嗨,我在另一个类中调用一个类时遇到一些问题,下面的代码 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();
4

2 回答 2

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();
于 2013-02-28T07:14:45.263 回答
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();
于 2013-02-28T07:17:19.063 回答