Can codeigniter support Inline functions.?

227 views Asked by At

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

There are 3 answers

0
Kevin On BEST ANSWER

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');
    }
}
0
RichardBernards On

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.

1
MonkeyZeus On

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

}