How does callback work in PHP?

1

I was studying a bit of 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, a callback that passes another function is passed as a parameter.

I have read the PHP documentation but I had difficulty understanding. A callback is used to call as a parameter a function inside another function, is it?

Thank you in advance.

    
asked by anonymous 08.04.2016 / 23:05

1 answer

5

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 by using the native call_user_func function to call a function by name. A callback in php can then 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
    
08.04.2016 / 23:23