php function arguments with a variable

Go To StackoverFlow.com

1

Is there a way to set up default function arguments with variables in them such as

function example($test = 'abc', $image = $scripturl . 'abc.png')
{
        // ...
}

The reason I want to do this is because I have sources that I have global variable settings with the path set up so that it is easy to grab when I need to include a css file or image.

The code above gives an unexpected T_VARIABLE...

2012-04-04 22:03
by MLM


3

That's not possible; default arguments must be constant.

You can easily emulate it like this though:

function example($test = 'abc', $image = null) {
    if($image === null) {
        global $scripturl;
        $image = $scripturl . 'abc.png';
    }
}
2012-04-04 22:10
by ThiefMaster
some OOP may be useful. Make $scripturl an object variable set upon construction, then it could be $this->scripturl - Eric Cope 2012-04-04 22:13
Ye, I guess this would be the only solution and to use it in the function :/ - Thanks for the reply - MLM 2012-04-04 22:39
don't forget global $scripturl; for external variables that aren't superglobal - craniumonempty 2012-04-05 11:59


4

Default values should be a constant. They should have the value, that is already available in compile time, not in a runtime.

2012-04-04 22:09
by zerkms
What I am proposing would be constant at compile since those settings would only change if the sources moved. I get your point but is there any way to do something the way I am proposing? I can always add in the variable in the function though... I think I will go with @ThiefMaster solutio - MLM 2012-04-04 22:38


1

No. Default values in function arguments must be constant values, not the results of expressions: http://php.net/manual/en/functions.arguments.php#functions.arguments.default

At the point the arguments are parsed, $scripturl will not exist anyways, and would always come out as NULL, since you couldn't make it global before it's used.

2012-04-04 22:10
by Marc B


1

well, as the error already stated, you cannot use a variable as (part of) default value in function signature.

what you can do however, is pass some known illegal value (null for instance) and then check inside the function and assign if needed:

function example($test = 'abc', $image = null)
{
   global $scripturl;
   if($image === null) $image = $scripturl . 'abc.png';
   ...
}
2012-04-04 22:10
by poncha
Ads