Search code examples
phpglobal-variablesdefaultuser-defined-functionsdefault-parameters

Using a Superglobal as a Default Function Parameter in PHP


There are multiple ways I can conceive for achieving the following functionality; however I am hoping for a super elegant solution. Can I use a PHP superglobal variable as the default value for a user defined function parameter?

Example:

function test1($foo=$_SERVER['PATH']) {
   echo $foo;
}

The above code spits out an error. Like I said I know that I can achieve the same thing using the following code (but the above code is more attractive):

function test2($foo) {
   if (!isset($foo)) $foo = $_SERVER['PATH'];
   echo $foo;
}

Thanks for the help!


Solution

  • I would recommend passing in the variable, but if you want to use a global one, you can do this

    function test2() {
        global $foo;
        ...
    }
    

    at the top of your function and set the value somewhere else, or go with your second idea - but you need to specify a default value in the function parameter to make it optional.

    function test2($foo='') {
       if (empty($foo)) $foo = $_SERVER['PATH'];
       echo $foo;
    }
    

    Another way to work with variables from outside your function is to pass them in by reference. This passes in a reference to the original variable, not a copy, so any changes you make inside the function will affect the original variable value outside of the scope of the function as well.

    $foo = 'bar';
    function test2(&$foo) {
       echo $foo;  // this will output "bar"
    }