2014-11-14 63 views
1

我們可以在Codeigniter的另一個函數裏寫多個函數嗎?這裏是我的控制器codeigniter可以支持內聯函數。

class Products extends CI_Controller { 

    public function myproduct() { 
     $this->load->view('myproduct'); // call myproduct.php 

      public function features() { 
       $this->load->view('features'); // call "myproduct/features" 
      } 

      public function screenshots() { 
       $this->load->view('screenshots'); // call "myproduct/screenshots" 
      } 
    } 
} 

根據我的控制器,myproduct()中有2個內聯函數。我的目標這一領域的空白顯示URL作爲

localhost/mysite/products/myproduct 
localhost/mysite/products/myproduct/features 
localhost/mysite/products/myproduct/screenshots 

我已經嘗試過,但它給了我一個錯誤

Parse error: syntax error, unexpected 'public' (T_PUBLIC) in D:\...........\application\controllers\mysite\products.php on line 5 

和5號線是

public function features() { ......... 
+0

爲什麼你需要˚F函數內部的聯繫? 'myproduct'方法中的 – 2014-11-14 13:23:51

+0

參數和條件解決。你不能在裏面添加任何方法, – 2014-11-14 13:23:52

+0

不,你不能在方法內加載一個方法,而且你真的不想。你想從中得到什麼? – 2014-11-14 13:30:09

回答

0

你可以只把它當作URL中的URI paramater:

public function myproduct($param = null) 
{ 
    if($param == null) { 
     $this->load->view('myproduct'); 
    } elseif($param == 'features') { 
     $this->load->view('features'); 
    } elseif ($param == 'screenshots') { 
     $this->load->view('screenshots'); 
    } 
} 
+0

謝謝幽靈。 – 2014-11-15 06:14:43

+0

@ShifanaMubi確定男人很高興這有幫助 – Ghost 2014-11-15 06:30:44

0

這是不是在笨。 ..這在PHP中通常是不可能的。你可以使用閉包,但是它們不會在你的情況下呈現所需的效果。

嘗試閱讀CodeIgniter URI Routing以瞭解codeigniter內路由的原理。在控制器中創建單獨的功能。

0

我不知道你想什麼來實現,或者你打算如何調用/使用這些功能,並在其範圍內,但在爲了聲明函數內部函數你這樣做:

public function myproduct(){ 

    $t = 'myproduct'; 

    $features = function($t = '', &$this = ''){ 
     // some code goes here 

     $this->load->view('features'); // will NOT work 

     $this->load->view($t.'/features'); // this should work 
    }; 

    $features($t, $this); // load the features view 

} 

這應該是你的目標,但:

public function myproduct($uri_piece = ''){ 

    $this->load->view('myproduct/'.$uri_piece); 

} 
+0

我認爲'$ this'和'$ t'都不在匿名函數的範圍內。 – Karolis 2014-11-14 14:51:34

+0

@Karolis謝謝,我忘了這不是Javascript哈哈 – MonkeyZeus 2014-11-14 14:56:44