Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    How do I pass a variable out of a function?

    I've designed some validation functions for my forms, and they're working awesome. The only thing is that I'm having a really hard time figuring out how to get variables that are declared within the function OUT of the function to the page the function is used. Here's one of the functions:

    PHP Code:
    function CheckLength($variable$max_length) {
        
    //check if variable is too long
        
    if (strlen($variable) > $max_length) {
            
    $Error_Stat 1;
            
    $Message Error('"' $variable '" is too long.  Please enter ' $max_length ' or less characters.');
            return 
    FALSE;
        }

    Pretty simple. Then I call it like this:

    PHP Code:
    $first_name $_POST['first_name'];

    $first_name CheckLength($first_name20); 
    The function works, but when I try to check against $Error_Stat and print the $Message, nothing happens. I've already read that this is because the variables declared in the function stay local, but I couldn't find out how to get around this other than using global, which I've heard is a bad idea.

    So how do I get $Error_Stat and $Message out of the function and to the page it's on without using global?

  • #2
    Supreme Overlord Spookster's Avatar
    Join Date
    May 2002
    Location
    Marion, IA USA
    Posts
    6,278
    Thanks
    4
    Thanked 83 Times in 82 Posts
    Making a variable global in scope is not in itself bad. In your case since you are likely not designing a major application I think it is perfectly fine. If you were designing this using object orientation which you would want to if this were going to be a large app then you would want to worry more about how you handled the scoping of your variables. Just declare it outside the function and you will be fine.

    And if you really wanted to since you said you have multiple form validation functions you could just go ahead and design a form validation class and work with it that way. Working with objects is much nicer than dealing with random scraps of codes and functions. Would also give you practice if you ever design any larger applications.
    Last edited by Spookster; 02-27-2007 at 10:06 PM.
    Spookster
    CodingForums Supreme Overlord
    All Hail Spookster

  • #3
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts
    Some great advice, especially on learning objects/classes. I will eventually take a trek on that endeavor. Thanks Spook!

    Here's the issue I'm having with declaring the two variables as global. Normally when I set $Message, the variable gets cleared on the next visit to the page. So basically, normally I just simply put:

    PHP Code:
    <?=$Message?>
    And if $Message is blank, it does nothing, but if $Message has something, it prints it. Then, the next time I go to the page, $Message is blank again (unless it's been set by something again).

    But, as you know, when I set $Message as global and echo it on the page, it will continue to be the global value until I change it or unset it...it doesn't clear itself on each pass to the page. So I'm finding that now, I have to use:

    PHP Code:
    <?=$Message?>
    <?php 
    unset($Message);
    Which just seems messy. Is there something I'm missing here?

  • #4
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,793
    Thanks
    19
    Thanked 156 Times in 147 Posts
    Here's one way:

    PHP Code:
    <?

    $first_name 
    "Joe";

    if (
    CheckLength($first_name20) !== true)
    {
        
    $error CheckLength($first_name20);
        die(
    $error['Error_Stat'].": ".$error['Message']);
    }

    $first_name "JoeJoeJoeJoeJoeJoeJoeJoeJoeJoeJoeJoeJoeJoeJoe";

    if (
    CheckLength($first_name20) !== true)
    {
        
    $error CheckLength($first_name20);
        die(
    $error['Error_Stat'].": ".$error['Message']);
    }



    // functions

    function CheckLength($variable,$max_length)
    {
        
    //check if variable is too long
        
    if (strlen($variable) > $max_length)
        {
            
    $error['Error_Stat'] = 1;
            
    $error['Message'] = '"' $variable '" is too long.  Please enter ' $max_length ' or less characters.';
            return 
    $error;
        }
        else
        {
            return 
    true;
        }
    }

    ?>
    Edit: If you have many functions/methods, and you want to output all of the errors at once, or store them all in the same array, try some OOP like Spookster said...
    Last edited by chump2877; 02-27-2007 at 10:21 PM.
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!

  • #5
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    I don't get why you are assigning the result of your CheckLength() function to $first_name.

    Anyways... I like to keep an error array like Chump mentioned and I like to make it global to all functions. It not encapsulated, sure, which potentially can lead to problems, but limited use of global can be really handy.

  • #6
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    This is what I do for all functions that I write that produce more than 1 variable.

    PHP Code:
    function validate($data) {
        
    $valid false;
        
    $message 'The data is not right';
        return array(
    'valid' => $valid'message' => $message);
    }

    $result validate('this is some data');
    if (!
    $result['valid']) {
        echo 
    'Error: ' $result['message'];


  • #7
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    yet another approach is to pass $message into the function by reference:

    PHP Code:
    function checkLength($string,$max_length,&$message='') {
      if(
    string is too long) {
        
    $message 'String is too long';
        return 
    false;
      }
      return 
    true;
    }

    //usage:
    $string='a long string'
    $check checkLength($string,3,$message);
    echo 
    $message//outputs 'String is too long' 
    My thoughts on some things: http://codemeetsmusic.com
    And my scrapbook of cool things: http://gjones.tumblr.com


  •  

    Posting Permissions

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