简体   繁体   English

CodeIgniter将参数传递给CORE MY_Controller中的函数

[英]CodeIgniter passing parameters to a function in CORE MY_Controller

I hope that this is possible 我希望这是可能的

Can I pass parameters to functions in CORE/MY_Controller? 我可以将参数传递给CORE / MY_Controller中的函数吗?

I am developing a application that has three controllers and most of the functions are the same so I want to code functions ones and use them again in their respectable controllers when need. 我正在开发一个具有三个控制器的应用程序,大多数功能是相同的,因此我想对功能进行编码,并在需要时在它们可敬的控制器中再次使用它们。

function like search_User_Name() will be in both of the controllers, it will be cool if i can get to code it once and reuse it. 像search_User_Name()之类的函数将在两个控制器中,如果我可以编写一次代码并重用它,那将很酷。 the problems that i am facing at the moment are 我目前面临的问题是

  1. The MY_Controller.php is not in the same folders as other controllers MY_Controller.php与其他控制器不在同一个文件夹中
  2. The search_User_Name() function has to receive parameters like search_User_Name($var1, $var2) search_User_Name()函数必须接收诸如search_User_Name($ var1,$ var2)之类的参数

I have a controller in the core folder as MY_Controller 我在核心文件夹中有一个控制器作为MY_Controller

class MY_Controller extends CI_Controller{

    public function __construct() {
             parent::__construct();
    }

    public function Testing($var){
     $function_var= $var;
     return $function_var;
   }
}

and i have a controller in the controller folder as Sub_Controlller 我在控制器文件夹中有一个控制器为Sub_Controlller

class Sub_Controller extends MY_Controller{
    public function __construct() {
        parent::__construct();
    }

    public function Show(){
        echo($this->Testing());
    }
}

on the view i have 在我看来

echo anchor('Sub_Controller/Show/Parameter','Pass a parameter');

according to my understanding i was spouse to get the word "parameter" on the screen. 根据我的理解,我是在屏幕上看到“参数”一词的伴侣。 can any help? 可以帮忙吗?

It will work fine, but you still need to pass in the arguments: 它将正常工作,但是您仍然需要传递参数:

class Sub_Controller extends MY_Controller {
    public function Show($arg = null) {
        echo($this->Testing($arg));
    }
}

Alternatively you can read the URI segment from the base function, but then you have less control: 或者,您可以从基本函数中读取URI段,但是您的控制较少:

class MY_Controller extends CI_Controller {
    public function Testing() {
        $function_var = $this->uri->segment(2);
        return $function_var;
   }
}
class Sub_Controller extends MY_Controller {
    public function Show() {
        echo($this->Testing()); // prints the argument in the URL
    }
}

Better to do it the first way. 最好以第一种方式进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM