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; } } 
1
  • yes this is possible. just make sure those 2 lines are before the call of myFunction(). Commented Mar 26, 2019 at 1:13

2 Answers 2

0

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

$pdo=PDOconnection; function myFunction($input = null){ if($input === null){ $input=$GLOBALS['pdo']; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

The only issue with this is that it prevents passing null as a value.
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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.