如何在codeigniter中设置私有类以形成验证回调


How to set private class to form validation callback in codeigniter

假设这是我的控制器。(复制自CI文档)

<?php
class Form extends CI_Controller {
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
        $this->form_validation->set_rules('password', 'Password', 'required');
        $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('myform');
        }
        else
        {
            $this->load->view('formsuccess');
        }
    }
    public function username_check($str)
    {
        if ($str == 'test')
        {
            $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}
?>

但是username_check($str)函数是公共的。根据CI文档,如果我想创建一个私有方法,我需要像这样添加"_"

private function _utility()
{
  // some code
}

但是,我如何将username_check()设置为私有并从表单验证set_rules中回调呢?

我是否应该使用DOUBLE下划线"__",即callback__username_check

您可以像已经做过的那样声明您的私有函数:

function _username_check()
{
  // some code
}

在验证规则中,使用:

callback__username_check

正如我所看到的,这一定很好!

记住:

_前缀会保护您的函数隐私,因此您实际上不必使用关键字private来声明函数,就可以让form_validation类访问该函数!