2

In php, this can be done:

function foo( $var = "bar" ){
    echo $var;
}

foo();         // output : bar

foo("cheese"); // output : cheese

I've tried to use a function instead like so:

function foo( $var = get_defined_vars() ){}

Which returned a parse error:

Parse error: syntax error, unexpected '(', expecting ')'

the obvious answer is the pass the variable like so

function foo( $var ){
    // do stuff
}

foo( get_defined_vars() );

however, the function is overloadable and can handle many params.

I usually use the function like:

foo( $var1, $var2, $var3 ... etc );

However I NEED the defined vars from the scope above the foo function, which means EVERYTIME I use the foo function I have to pass get_defined_vars().

I find it pretty annoying how everytime I want to use this function I have to call get_defined_vars(); Like so:

foo( get_defined_vars(), $var1, $var2, $var3 ... etc );

So PLEASE can anybody think of a way to over come this?

I tried this, also to no avail:

function foo(){
    $args = func_get_args();
    array_unshift( get_defined_vars() );
    call_user_func_array( "bar", $args );
}

function bar(){
    // do stuff
}
4

2 回答 2

2

No, you can't. Like for properties only static values and arrays are allowed. Even if, I would not recommend it, because it makes a function call unpredictable.

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

http://php.net/functions.arguments#example-152

于 2012-07-04T09:59:09.773 回答
0

尝试以下方式:

function foo( $var1, $var2, $varForDefinedVars=null ){
  if (is_null($varForDefinedVars)){
     $varForDefinedVars = get_defined_vars();
  }
}
于 2012-07-04T10:04:57.983 回答