...

View Full Version : Var inside a function



ninnypants
03-05-2009, 12:03 AM
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:


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:


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;
}

Fou-Lu
03-05-2009, 12:09 AM
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

$hello = 'Hello';

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

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

?>

Output:


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).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum