Function returning nothing same as returning NULL?

Let’s say I have the following function:

function escape($var)
{
    if (is_string($var) && $var !== '') {
        return htmlspecialchars($var, ENT_QUOTES, 'UTF-8');
    }
}

If the $var isn’t a string or is an empty string, the function returns nothing. Is that the same as if I stuck a “return NULL” in there?

When I test this out for real, a function that returns nothing does “appear” to return NULL, but can this be relied upon? I’m wondering if there’s some exception where I can’t rely on this behavior being equal to NULL.

A function that returns nothing returns null. However, null !== ‘’. On the other hand, null == ‘’ because when loosely compared null and ‘’ are false.

Try this:



function escape($var=NULL)
{
	if (is_string($var) && $var !== '') {
	  $var = htmlspecialchars($var, ENT_QUOTES, 'UTF-8');
	}
	
	return $var;
}


.

http://www.php.net/manual/en/functions.returning-values.php

Thanks for confirming this. I was just wondering if this was consistent behavior that could always be relied upon. I’ve always explicitly returned something, even null, and wondered if returning nothing could result in some phantom bug somewhere, somehow.

Thanks. That’s a simple, smart approach.

guido2004’s link above states:

Note: If the return() is omitted the value NULL will be returned.

Well, that settles it. Thanks.

Thanks everyone for your responses.