SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Function returning nothing same as returning NULL?

    Let's say I have the following function:
    Code:
    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.

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,147
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    A function that returns nothing returns null. However, null !== ''. On the other hand, null == '' because when loosely compared null and '' are false.

  3. #3
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,833
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Try this:

    PHP Code:

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




    .
    Learn how to be ready for The New Move to Discourse

    How to make Make Money Now with a *NEW* look

    Be sure to congratulate Patche on earning Member of the Month for July 2014

  4. #4
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,496
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)

  5. #5
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by oddz View Post
    A function that returns nothing returns null.
    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.

    Quote Originally Posted by John_Betong View Post
    Try this:
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •