Doubt about functions in php

Asked

Viewed 41 times

-1

A function only works if we call it in some file or it will work anyway? For example, to pass the value from one variable to another in the processing file, I know I must call the function to give value to the variable. But when I just want to pass a value from one string to another string, for example:

public function conta_teste_profissional($codigo){
    $conexao = Database::getConnection();
    $busca = "SELECT * FROM teste WHERE cod_usuario_profissional = $codigo;";
    $resultado = $conexao->query($busca);
    $retorno = $resultado->fetchAll(PDO::FETCH_ASSOC);

    $tamanho = count($retorno);
    return $tamanho;
}

.

I need to call it in some other file or this function will work automatically?

  • Try to be more specific in your doubt...

  • The question is not very clear to me, to be executed, a function needs to be called idependentemente from the file (since it has been loaded). What would be "will work anyway"?

2 answers

1

Your question is not very clear, but if the question is "functions are invoked automatically" the answer is no. You should call the function in each part of your code that you want to use it. Taking your example as the basis

public function conta_teste_profissional($codigo){
    $conexao = Database::getConnection();
    $busca = "SELECT * FROM teste WHERE cod_usuario_profissional = $codigo;";
    $resultado = $conexao->query($busca);
    $retorno = $resultado->fetchAll(PDO::FETCH_ASSOC);

    $tamanho = count($retorno);
    return $tamanho;
}

The above block will only be responsible for declaring the function, if you want to use it, you should call it in the location that is suitable for you. Example:

conta_teste_profissional(4)
  • That’s right. Very nice to know, thank you!

0

Functions, even if declared, are not automatically invoked/initiated. You should call the function in the part of your code where you need it.

Using your code as an example:

public function conta_teste_profissional($codigo){
    $conexao = Database::getConnection();
    $busca = "SELECT * FROM teste WHERE cod_usuario_profissional = $codigo;";
    $resultado = $conexao->query($busca);
    $retorno = $resultado->fetchAll(PDO::FETCH_ASSOC);

    $tamanho = count($retorno);
    return $tamanho;
}

The function would only be executed if you called it that way:

conta_teste_profissional(10); //Exemplo

You can also call a declared function in another PHP file by giving a include in the file in which it is declared.

Here is the manual on INCLUDE: http://php.net/manual/en/function.include.php

Browser other questions tagged

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