php - 如何在 codeigniter 中设置私有(private)类以形成验证回调

标签 php codeigniter

假设这是我的 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/

相关文章:

codeigniter - PhpStorm 无法识别类中的 CodeIgniter v3.0 数据库方法

php - 无法将图像上传到codeigniter中的数据库

database - 通过 CodeIgniter 在数据库中保存 session

Codeigniter 表单验证。阿尔法和空格

php - PHP PDO 语句可以接受表名或列名作为参数吗?

javascript - 当客户端修改两个按钮的 javascript 函数参数相同时,SQL/PHP 会更新多行

php - 了解 Doctrine 级联操作

php - 使用bootstrap 3音频播放器,但显示正常的html5输出

php - 通过php流文件

php - 正则表达式帮助(适用于 PHP)