Return always return false

2019-03-05 09:04发布

问题:

The problem is that this function always return me 0. Why?

public function valid_token ()
{
    if (!isset($_SESSION['token']) || $this->token != $_SESSION['token'])
    {
        $this->errors[] = "Formulario incorrecto";
    }

return count($this->errors)? 0 : 1;
}

回答1:

Edit:

Ignore my previous answer. Stupid falsy values. The reason you are always getting a 0 in return is simply because...you have a value inside of your array. As @Orangepill states in the comments, dump the values of $this->token and $_SESSION['token] to see what's going on.

Old:

count() returns the number of elements inside an array. Right now you are just running count(). You need to compare it to an integer value i.e.:

count($this->errors)>0 ? 0 : 1;


回答2:

Token is a mt_rand function, that why I think the problem is at the return statement. Also because I get error even when I call another function called valid_data(), that has the same return statement. $token = $_SESSION['token'] = md5(uniqid(mt_rand(), true));



回答3:

Did you initialize $this->errors in your class before using it in valid_token()? If not, you may be counting something that is not set, which would return false. Make sure you initialize the member like this:

protected $error = array();

or

public $error = array();

Also, you used a ternary expression but you didn't wrap the condition in parentheses. Therefore, the statement might not have evaluated properly. Try this:

 $isValidForm = (count($this->errors) > 0) ? false : true;
 return $isValidForm;

I agree that you should "dump" the variables to see what your getting back. I would do this by logging their string values to the Apache error.log:

error_log("this token: " . print_r($this->token, true));

error_log("session token: " . print_r($_SESSION['token'], true));

error_log("this error: " . print_r($this->error, true));

In GNU / Linux or OSX You can tail the log from the console like this:

tail -f /var/log/apache2/error.log

This way you don't have to interrupt the flow of the program to debug it.

Finally, and this is just a suggestion -- valid_token() is not a good method name, it sounds like a variable name. validate_token() or validateToken() are better names because they use verbs to signify that they're actions.



标签: php oop class