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...

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 solution
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';
    }
}

3 Comments

some OOP may be useful. Make $scripturl an object variable set upon construction, then it could be $this->scripturl.
Ye, I guess this would be the only solution and to use it in the function :/ - Thanks for the reply!
don't forget global $scripturl; for external variables that aren't superglobals
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.

Comments

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';
   ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.