在Thinkphp中,實例化對象有這么幾種方法,如果是類,有A和R方法,區別是A方法只是對象的實例化,而R方法是可以同時實例化對象里面的方法的,這里需要去指定,如下面的實例代碼:
1 <?php 2 namespace Admin\Controller; 3 use Think\Controller; 4 5 class GoodsController extends Controller{ 6 public function showlist(){ 7 8 //實例化控制器A方法 9 $test=A("Manager"); 10 echo $test->test1(); 11 12 echo "<br/>"; 13 14 //也可以去跨模塊調用 15 $test_m=A("Home/Goods"); 16 echo $test_m->test(); 17 18 echo "<br/>"; 19 //R方法可以取執行對應模塊下面的 20 R("Home/Goods/test"); 21 // $this->display(); 22 } 23 }
從上面可以看出,R方法同時也可以去跨模塊去實例化。
另外我們在Model的數據模型里面,必然需要下面的兩種方法,一個是D方法,一個是M方法,前者是實例化數據模型類,而后者則是實例化數據模型的父類。
1 <?php 2 namespace Admin\Controller; 3 use Think\Controller; 4 class TestController extends Controller{ 5 public function test1(){ 6 $mythinkphp=M("user"); 7 $t=$mythinkphp->select(); 8 echo "<pre>"; 9 // var_dump($mythinkphp->select()); 10 // echo count($t); 11 // echo "<br/>"; 12 // echo count($t[1]); 13 // echo "<br/>"; 14 // for($i=0; $i<count($t); $i++){ 15 // if($t[$i]['name']=='xuning'){ 16 // echo "存在這個用戶,用戶ID為".($i-1); 17 // } 18 // } 19 // echo "<br/>"; 20 //這樣就完成了從數據庫里面去遍歷數據 21 echo "<center>"; 22 echo "<h1>This is table test content</h1>"; 23 echo "<table border='1px'>"; 24 for($i=0; $i< count($t); $i++){ 25 echo "<tr>"; 26 echo "<td>"; 27 echo $t[$i]['id']; 28 echo "</td>"; 29 echo "<td>"; 30 echo $t[$i]['name']; 31 echo "</td>"; 32 echo "<td>"; 33 echo $t[$i]['password']; 34 echo "</td>"; 35 echo "</tr>"; 36 } 37 echo "</table>"; 38 echo "</center>"; 39 echo "</pre>"; 40 $t2=D("test_1"); 41 $temp=$t2->select(); 42 echo $temp[0]['name']; 43 } 44 public function test2(){ 45 //其實這里的實例化是建立的數據庫對象,並不是精確到表,同時 46 //我們也可以不是建立數據模型,從而直接使用,所以, 47 $t=new \Model\TestModel; 48 show_bug($t); 49 } 50 public function test3(){ 51 $user=D("Test"); 52 show_bug($user); 53 } 54 }
雖然從用法上看不出什么差別,但是內部確實不同的,D方法只實例化定義的數據模型類,而M方法去實例化數據模型的父類。
參考http://blog.csdn.net/mycodedream/article/details/45340949