2013-02-28 106 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();