开发者

Simple PHP Function Boolean Problem

开发者 https://www.devze.com 2023-02-25 01:40 出处:网络
Someone please explain to me why this doesn\'t work, and what I am doing wrong. For some reason, when I run the function validateUsername, the $error variable remains completely unchanged, instead of

Someone please explain to me why this doesn't work, and what I am doing wrong. For some reason, when I run the function validateUsername, the $error variable remains completely unchanged, instead of evaluating to true. How is this possible?

Yet, if I remove the code within the function and run it straight without a function call, it works. The 开发者_StackOverflowexample below is so simple it is practically pseudo code, and yet it doesn't work. Is this behavior unique to PHP? I don't want to run into this again in some other language.

<?php

$username = 'danielcarvalho';
$error = false;

function validateUsername()
{
    if (strlen($username) > 10)
    {
        $error = true;
    }
}

validateUsername();

if ($error == false)
{
    echo 'Success.';
}
else
{
    echo 'Failure.';
}

?>


This isn't working because $username isn't available within the scope of your validateUsername function. (Neither is the $error variable.) See the variable scope section of the PHP manual for more information.

You could fix this by adding global $username, $error; within your function, although this isn't a particularly elegant approach, as global variables are shunned for reasons too detailed to go into here. As such, it would be better to accept $username as an argument to your function as follows:

<?php
    function validateUsername($username) {
        if (strlen($username) > 10) {
            return false;
        }

        return true;
    }

    if (validateUsername('danielcarvalho')) {
        echo 'Success.';
    }
    else {
        echo 'Failure.';
    } 
?>


$error has local scope in function validateUsername. To access global variables, use global keyword.

Read about scopes here. Change your function to:

function validateUsername($username)
{
    global $error;
    if (strlen($username) > 10)
    {
        $error = true;
    }
}

validateUsername($username);

Better implementation using function parameter:

function validateUsername($username, &$error)
{
    if (strlen($username) > 10)
    {
        $error = true;
    }
}
validateUsername($username, $error);

Another implementation:

function validateUsername($username)
{
    if (strlen($username) > 10)
    {
        return true;
    }
    return false;
}
$error = validateUsername($username);
0

精彩评论

暂无评论...
验证码 换一张
取 消