Calling function in a controller from a parameter sent by the user in PHP

Asked

Viewed 102 times

0

I am building an application that from the information the user sends me on a GET I will run a function. EX:

//classe
class Page extends CI_Controller {

    public class index($param){ 
      //aqui estou procurando algo semelhante a $this->"$param"();
    }

    private class foo(){ echo 'foo'; }
    private class bar(){ echo 'bar'; }

}

For the above example, if my user sent to the function index('foo') he would have to perform the function $this->foo(). Could someone show me how I can do my job index() perform another function depending on the sent parameter?

  • 1

    You need to create routes to your application, the controller should not be responsible for directing actions other than redirects in isolated cases. Here’s an example: http://laravel.com/docs/5.1/routing - It’s a bit boring to do without a framework, but it’s possible, I have a route system that I made for my own use and works as well as frameworks.

1 answer

1

For you to do this is simple.

Let’s create a controller called for example test and inside him do what you need:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Teste extends CI_Controller {

    public function __construct(){

        parent::__construct();
    }

    public function ver($param){
        echo $this->$param();
    }
    private function foo(){
        echo 'foo';
    }
}

Go to the URL and pass the command as an example:

http://localhost/test/ver/foo

Will display

foo

if you want to create a controller to control every application and leave the URL organized, you can use Rotas, that is a good and easy way out:

http://codeigniterbrasil.com/configuracoes/configuracao-rotas-routes-codeigniter/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.