Nested return in PHP

Asked

Viewed 28 times

0

public function form($request)
{
    $cadastro = $this->cadastrar(['cpf' => $request['cpf'], 'nome' => $request['nome']]);

    if ($cadastro) {

        echo 'CPF cadastrado com sucesso';

    } else {

        echo 'Erro ao cadastrar CPF'    

    }

}

public function cadastrar($dados)
{
    if ($this->validar($dados['cpf']))
        return false;

    // Lógica para cadastro dos dados aqui....

}

public function validar($cpf)
{
    $valido = true;

    // Lógica para validação de CPF aqui....

    return $valido;

}

In the above example the function form() receives the request data and invokes the function cadastrar() to register a CPF. In function cadastrar() this CPF is validated by invoking the function validar.

If the reported CPF is invalid, a boolean is returned from the function validar() for the function cadastrar() and then a boolean is sent from the function cadastrar() for the function form().

It is possible (in case the CPF is invalid) to send the function return validar() directly to the function form()?

Note: The example quoted above is just an abstraction of the idea. Therefore, validate the CPF directly in the function form() would not be a solution alternative to the problem. The idea is to eliminate the 'nested return' of responses between functions (if possible of course).

  • 1

    Despite what you say at the end, it would make more sense to call the validation function from the form function. The way you did, the registration function has an extra responsibility.

  • @bfavaretto As I said, this example I gave is just an abstraction. I have a slightly more complex code in production, where the principle of responsibility applies. Not to expose a very large code, I preferred to exemplify this way.

  • Personally, I don’t remember any special PHP feature that might accomplish this goal, but just in case, I decided to bring the topic up for discussion in the Stack Overflow community.

No answers

Browser other questions tagged

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