More than one return on a method in PHP

Asked

Viewed 238 times

0

For example I have the following function:

<?php

public function login($username, $password) {
  if($condicao === 1) {
     return true, 
  } elseif($condicao === 2) {
    return 'qualquer string';
  } else {
    return false;
  }
}

How do I use this way a function with 3 or more returns, with two users like this:

if($login->login($username, $password)) {
  echo 'foi';
} else {
  echo 'não foi';
}

I could tell?

EDITED

if (count($cookie) === 12) {
    Session::set('ct0', $ct0[0]);
    return true;
} elseif (count($cookie) === 13) {
    return 'bloqued';
} else {
    return false;
}

Let’s assume that the above example is a function made with curl where if there is correct login and password returns me true, if the account is blocked, returns me 'bloqued', if the entered data is wrong returns me false;

Thus remaining:

public function login($username, $password) {
    curl...

    if (count($cookie) === 12) {
        return true;
    } elseif (count($cookie) === 13) {
        return 'bloqued';
    } else {
        return false;
    }
}


// Modo de usar

if ($login->login($username, $password)) {
    echo json_encode([
            'error'     => false,
            'message'   => 'Logado com sucesso, aguarde...'
        ]
    );
} elseif($login->login($username, $password) !== true && $login->login($username, $password) !== false) {
    echo json_encode([
            'error' => true,
            'message' => 'Conta bloqueada',
        ]
    );
} else {
    echo json_encode([
            'error'     => true,
            'message'   => 'Usuário e/ou Senha incorretos'
        ]
    );
}
  • The variable $condicao exists ?

  • is just an example I tried to explain, I want to know how I use a function that returns more than three values. Understand?

  • No. Does it make sense to have three different returns in the role, especially when dealing with different types? And what exactly do you want to check with the if?

  • There’s an error in the first line return, 'cause you’re using , which has to be ;

  • @Wéllingthonm.Souza, yes it was typo I made the code right here, Anderson Carlos Woss, I will edit the topic.

  • @Crazy Dev, you can see it works with more returns ideone.. It would be good to put more information about the code.

  • I edited the question, @Wéllingthonm.Souza I tried with a similar example that you put in the comments and could not.

  • $cookie is a Array ?

  • Exact. Yes is an array, only $cookie[4] removed some strings.

Show 4 more comments

2 answers

1


There are several ways, in fact what you want is not "More of a return", including.

But you could do:

const ERR_MENOR_QUE_UM = 0;
const ERR_MAIOR_QUE_VINTE = -1;
const ERR_DIVISIVEL_POR_DOIS = -2;

function verificarNumero($n)
{
    if($n < 0){
        return ERR_MENOR_QUE_UM;
    }

    if($n > 20){
        return ERR_MAIOR_QUE_VINTE;
    }

    if($n % 2 === 0){
        return ERR_DIVISIVEL_POR_DOIS;
    }

    return true;
}

That way it would be enough to do:

if(verificarNumero(2) === true){
    echo 'Nenhum erro ocorreu';
}

If not, as is the case, you would have three possible outcomes:

if(verificarNumero(2) === ERR_DIVISIVEL_POR_DOIS){
    echo 'Número inválido, divisível por dois';
}

You can also use switch for such purpose.


Now if you want to return more than one value you can actually use an array:

function fatorial($n)
{
    $f = array_product(range($n, 1));

    if ($f >= PHP_INT_MAX) {
        return [$f, true];
    }

    return [$f, false];
}

Now in fact you return two values, this is not very common in PHP, although this may be extremely common in other languages. You too could do only return [array_product(range($n, 1)), $f >= PHP_INT_MAX];, but I believe this would be more confusing.

To use this you could do:

list($resultado, $erro) = fatorial(10);

if($erro === false){
  echo $resultado;
}else{
  echo 'Algo deu errado';
}
  • It worked but I can’t verify the amount of cookies, for example: an account with correct data receives so many cookies, an account with wrong data receives so many cookies, and an account blocked on twitter receives another amount of cookies. :(

1

Change the condition of:

// Modo de usar

if ($login->login($username, $password))

To:

// Modo de usar

if ($login->login($username, $password) === true)

See this article: When to use == or === in php? on Blog da Alura.

  • Almost got it. problem now is in the counting of cookies

  • 1

    @Crazy dev, good, consider marking as useful, now for this other problem, I recommend opening another question.

Browser other questions tagged

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