假设这是我的 Controller 。 (从 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)方法,我需要像这样添加 "_"。
private function _utility()
{
// some code
}
但是如何将 username_check() 设置为私有(private)并从表单验证 set_rules 回调?
我应该使用双下划线 "__" 即 callback__username_check 吗?
最佳答案
你可以像你已经做的那样声明你的私有(private)函数:
function _username_check()
{
// some code
}
在验证规则中,使用:
callback__username_check
正如我所见,这一定工作得很好!
记住:
_
前缀会保护你的函数隐私,所以你真的不必使用关键字 private
来声明函数让 form_validation
类访问该函数!
关于php - 如何在 codeigniter 中设置私有(private)类以形成验证回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34575579/