Get uri segment in index function of controller -

2019-05-31 13:14发布

问题:

I have a url

www.xample.com/app/pay/11

where pay is my controller. The controller is defined as

class Pay extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->library('tank_auth');
        $this->load->model('users');
    }

    function index()
    {
        //How can I get 11 from uri ?
    }
}

Im not using any additional function here.Im using an index function.How could I get the value 11?

回答1:

You could use _remap() to run the index() function for anything sent to this class.

class Pay extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->library('tank_auth');
        $this->load->model('users');
    }

    function _remap($method, $params=array())
    {
        $methodToCall = method_exists($this, $method) ? $method : 'index';
        return call_user_func_array(array($this, $methodToCall), $params);
    }

    function index($val)
    {
        echo $val;
    }
}

Now, when you go to www.xample.com/app/pay/11, index() will be called.



回答2:

You can use the URI Segment class of codeigniter.. it like $this->uri->segment(n)

In your case, you need to get the 3rd segment.

Hence, it will be-

echo $this->uri->segment(3);


回答3:

http://localhost/abc/sellers/YWRtaW4=

http://localhost/abc/sellers/follow/u/1

function _remap($method, $params=array())
    {
        $method_exists = method_exists($this, $method);
        $methodToCall = $method_exists ? $method : 'index';
        $this->$methodToCall($method_exists ? $params : $method);
    }


function index($username) {
        echo $username;
}

function follow($param){
   print_r($param);
}

Try to use this function..



回答4:

enable url helper in config/autoload.php

$autoload['helper'] = array('url');

or load url helper in desired controller or its method

$this->load->helper('url');

and then use below in controller

$this->uri->segment(3);