0

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

2 Answers2

0

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

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

@Nick's answer should work. This might be a little simpler?

$pdo=PDOconnection;

function myFunction($input = null){
    if($input === null){
        $input=$GLOBALS['pdo'];
    }
}
Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
  • The only issue with this is that it prevents passing `null` as a value. – Nick Mar 28 '19 at 00:21
  • There's always going to be some value that makes no sense whatsoever to pass in, whether `null`, `false`, `true`, `0`, `"nope"` or whatever. `null` seemed to fit the example given. – Greg Schmidt Mar 28 '19 at 14:10