Daniel Carvalho
Daniel Carvalho

Reputation: 557

Simple PHP Function Boolean Problem

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 example 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.';
}

?>

Upvotes: 1

Views: 5581

Answers (2)

Ashwini Dhekane
Ashwini Dhekane

Reputation: 2290

$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);

Upvotes: 1

John Parker
John Parker

Reputation: 54445

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.';
    } 
?>

Upvotes: 7

Related Questions