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

时间:2016-01-03 10:38:52

标签: php 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

1 个答案:

答案 0 :(得分:2)

您可以像以前一样声明您的私人功能:

function _username_check()
{
  // some code
}

在验证规则中,使用:

callback__username_check

正如我所见,这必须正常工作!

请记住:

_前缀会处理您的函数隐私,因此您不必使用关键字private来声明函数让form_validation类访问该函数!