is that possible in PHP to pass variables into a function when they are not set as parameters? I mean something like the following:
$pdo=PDOconnection; $arr=someArray; function myFunction(){ if(no-parameters){ $input=$pdo; //or $input=$arr; } } is that possible in PHP to pass variables into a function when they are not set as parameters? I mean something like the following:
$pdo=PDOconnection; $arr=someArray; function myFunction(){ if(no-parameters){ $input=$pdo; //or $input=$arr; } } @Nick's answer should work. This might be a little simpler?
$pdo=PDOconnection; function myFunction($input = null){ if($input === null){ $input=$GLOBALS['pdo']; } } null as a value.null, false, true, 0, "nope" or whatever. null seemed to fit the example given.You could use func_num_args to check for the number of function arguments, and if the result is 0, get the value from the $GLOBALS array e.g.
$foo = 4; function myFunction () { if (!func_num_args()) { $input = $GLOBALS['foo']; } else { $input = func_get_arg(0); } echo "$input\n"; } myFunction('hello'); myFunction(); Output:
hello 4