CodeIgniter:为什么在回调函数之后变量会改变?我用对了吗?


CodeIgniter: Why variable change after callback function? Am I using it the right way?

我目前正在使用CodeIgniter。在表单验证之后,我使用函数"set_rules"来检查用户的信息是否正确。否则,我试图使用"回调"函数发送2个变量,但似乎第二个变量在我使用"回调"函数时改变了它的值。如果在我的表单中,我将它归档为:

Username = "test_username"    
Password = "test_password"   
在我的函数数据库中,
$username will display "test_username"       
$password will display "test_username,test_password".     

我试过了:

 function index()
 {
  $this->load->library('form_validation');
  $username = $this->input->post('username');
  $password = $this->input->post('password');
  $this->form_validation->set_rules('username', 'Username', 'trim|required', 'wrong or missing username');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database($username, $password)', 'wrong or missing password');
 }
  function check_database()
  {
    echo '$password'. '</br>'; //display => test_username
    echo '$username'. '</br>'; // display => test_username,test_password
  }

我试着用

替换几行高级代码:
 function index()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username', 'trim|required', 'wrong or missing username');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database['. $this->input->post($username). ','. $this->input->post($password), 'wrong or missing password'];
  function check_database($password, $username)
  {
    echo '$password'. '</br>'; //display => test_username
    echo '$username'. '</br>'; // display => test_username,test_password
  }

但这是同样的问题。我没有在CodeIgniter网站上找到回调函数的手册。第二个问题是当我写

  $this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database', 'wrong or missing password');
  function check_database() //work only if I write check_database($password)
  {
    //blah blah blah
  }

它弹出一个错误。鉴于我没有找到call_back函数的任何手册,我认为回调函数被用于测试密码变量的set_rules中,因此我认为call_back函数将自动将密码变量发送给check_database()函数。(这就是为什么我需要把$password放在check_database原型中)。

我已经找到了解决方案,但我只是想知道会发生什么(我很好奇)?

有没有人可以告诉我为什么在第一个和第二个代码,回调的第二个参数改变一旦它是在check_database() ?顺便问一下,你能确认一下我说的最后一个代码是否正确吗?更准确地说,当我说call_back函数将自动将密码变量发送给check_database()时?

谢谢的

PS:在我之前给你看的代码中,我自愿删除了一部分代码,以避免你阅读太多,因为我认为我的帖子有点长。

变量或值不变。在编码器表单验证中,回调第一个参数提供值。

$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database[x]');
....
function check_database($str, $param1)
{
     echo $str;   // password
     echo $param1; // x
}

如果您希望提供其他输入post参数,这更容易:

$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
function check_database($str)
{
     $username = $this->input->post('username'); // same input post value
     ....
}

希望对你有帮助。

http://www.codeigniter.com/user_guide/libraries/form_validation.html callbacks-your-own-validation-methods