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...
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';
}
}
global $scripturl;
for external variables that aren't superglobal - craniumonempty 2012-04-05 11:59
Default values should be a constant. They should have the value, that is already available in compile time, not in a runtime.
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.
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';
...
}