drpkcwwav20524605
drpkcwwav20524605
2014-11-14 12:58

codeigniter可以支持内联函数吗?

已采纳

Can we write multiple functions inside another function in Codeigniter.? here is my controlller

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"
            }
    }
}

as per my controller there are 2 inline functions inside myproduct(). my aim isto display the url as

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

i already tried it but it gives me a error

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

and the line 5 was

public function features() { .........
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doubengman2072 doubengman2072 7年前

    You can just treat this as a uri paramater in the url:

    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');
        }
    }
    
    点赞 评论 复制链接分享
  • dongti8535 dongti8535 7年前

    I am not sure what you are trying to achieve or how you plan to call/use these functions and in which scope but in order to declare a function inside a function you do this:

    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
    
    }
    

    This should be your goal though:

    public function myproduct($uri_piece = ''){
    
        $this->load->view('myproduct/'.$uri_piece);
    
    }
    
    点赞 评论 复制链接分享
  • dousi6405 dousi6405 7年前

    This is not something in codeigniter... This is generally not possible in PHP. You can work with closures, but they dont render the desired effect in your case.

    Try reading CodeIgniter URI Routing to understand the principles of routing within codeigniter. Than create the separate functions in controllers.

    点赞 评论 复制链接分享

为你推荐