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 2 of 2
  1. #1
    Regular Coder ninnypants's Avatar
    Join Date
    Apr 2008
    Location
    Utah
    Posts
    504
    Thanks
    10
    Thanked 47 Times in 47 Posts

    Var inside a function

    So I've read that when you use var inside of a php function it confines the those variables to the function, but on a function I created it breaks when I use it.

    Broken:
    PHP Code:
    function get_room($room){
        var 
    $rms = array('a''b''c''d');
        var 
    $htm '';
        for(
    $i=0$i<count($rms);$i++){
            
    $htm .= '<option value="'.$rms[$i].'"';
            if(
    $rms[$i] == $room){
                
    $htm .= 'selected="selected"';
            }
            
    $htm .= '>'.$rms[$i].'</option>';
        }
        return 
    $htm;

    Working:
    PHP Code:
    function get_room($room){
        
    $rms = array('a''b''c''d');
        
    $htm '';
        for(
    $i=0$i<count($rms);$i++){
            
    $htm .= '<option value="'.$rms[$i].'"';
            if(
    $rms[$i] == $room){
                
    $htm .= 'selected="selected"';
            }
            
    $htm .= '>'.$rms[$i].'</option>';
        }
        return 
    $htm;


  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    PHP has only one use for the var keyword. And thats in a member declaration for PHP4 objects.
    Using var in a function will cause a syntax error. What you're reading is referring to scope.

    PHP Code:
    <?php

    $hello 
    'Hello';

    function 
    helloAlter()
    {
        
    $hello 'world';
    }

    print 
    $hello "\n";
    helloAlter();
    print 
    $hello "\n";

    ?>
    Output:
    Code:
    Hello
    Hello
    The options for scope are to pass the desired value to change as a reference variable, or to use the dangerous global keyword. Globalizing is a last resort since it kills functions should the original variable be removed. This results in undesirable and unpredictable behaviour. The only time global should actually be used is when you're using a callback handler for a predefined PHP function that requires a specific signature, but you need to add additional variables (such as setting an error handler function that requires an open data source).
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


  •  

    Posting Permissions

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