How does callback work in PHP?

Asked

Viewed 2,727 times

2

I was studying a little PHP until I came across this code:

$this->form_validation->set_rules("nome", "nome", "required|min_length[5]|callback_nao_tenha_a_palavra_melhor");

public function nao_tenha_a_palavra_melhor($nome) {
    $posicao = strpos($nome, "melhor");
    if($posicao != false) {
        return TRUE;
    } else {
        $this->form_validation->set_message("nao_tenha_a_palavra_melhor", "O campo '%s' não pode conter a palavra 'melhor'");
        return FALSE;
    }

Within the form validation function is passed as a parameter callback calling another function.

I have already read the PHP documentation but I found it difficult to understand. A callback is used to call as a parameter a function within another function, is this ?

Thanks in advance.

1 answer

6


A callback is nothing more than the name or reference to a function that is passed as a parameter to another function, being invoked when convenient. In php we can do this using the call_user_func native function to call a function by name. A callback then in php can be used as follows:

function funcaoCallback($a){
  echo $a;
}

function funcaoQualquer($callback){
  //Faz algo aqui e quando tiver pronto chama a função que foi passada
  //com um parâmetro gerado dentro desse método
  call_user_func($callback, 'teste');
}

funcaoQualquer('funcaoCallback'); // exibirá teste como saída

Browser other questions tagged

You are not signed in. Login or sign up in order to post.