doushi1473 2013-06-11 16:55
浏览 46
已采纳

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

I hope that this is possible

Can I pass parameters to functions in 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. the problems that i am facing at the moment are

  1. The MY_Controller.php is not in the same folders as other controllers
  2. The search_User_Name() function has to receive parameters like search_User_Name($var1, $var2)

I have a controller in the core folder as 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

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?

  • 写回答

1条回答 默认 最新

  • dsbqfrr098575666 2013-06-11 17:05
    关注

    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:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大