2013-02-28 18 views
0

嗨我有一些問題要調用另一個類中的類,下面的代碼1可以顯示結果,但在2使用相同的代碼添加到另一個類,我不知道爲什麼這是不行的。
謝謝。在另一個類中調用一個類

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>"; 
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(); 
+0

爲什麼不工作?你想要完成什麼?你有什麼嘗試?你得到什麼錯誤? – L0j1k 2013-02-28 07:14:53

+0

閱讀:http://www.php.net/manual/en/language.variables.scope.php – deceze 2013-02-28 07:16:04

回答

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

另一種選擇是有$數據庫作爲類變量(聽起來更好)。然後執行以下操作:

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

這工作..謝謝你的回覆。 – user2118534 2013-02-28 07:31:16

+0

不用客氣 – hek2mgl 2013-02-28 07:35:39

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