Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
add comment

4 Answers

up vote 3 down vote accepted

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';
    }
}
share|improve this answer
    
some OOP may be useful. Make $scripturl an object variable set upon construction, then it could be $this->scripturl. –  Eric Cope Apr 4 '12 at 22:13
    
Ye, I guess this would be the only solution and to use it in the function :/ - Thanks for the reply! –  MLM Apr 4 '12 at 22:39
    
don't forget global $scripturl; for external variables that aren't superglobals –  craniumonempty Apr 5 '12 at 11:59
add comment

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

share|improve this answer
    
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 –  MLM Apr 4 '12 at 22:38
add comment

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.

share|improve this answer
add comment

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';
   ...
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.