0

A workaround was described here: PHP function as parameter default

But I was wondering why this doesn't work:

class Foo extends Bar {
function __construct($paramsIn=array("timestamp"=>time()-7200,"api-key"=>"blah"),                       
                         $urlIn="http://www.example.com/rest")
{ //...etcetc
}

I get the error:

Parse error: syntax error, unexpected '(', expecting ')' in filename.php

It's specifically related to the time() call.

0

1 Answer 1

3

The default value for function arguments only supports literals, that is strings, numbers, booleans, null and arrays. Function calls like time() are not supported. The reason for this is that the function signature should describe the interface and be independent of runtime values. The same applies to initializing object properties in a class.

As your link points out, the workaround is to use null and process it within the function body.

function __construct($paramsIn=array("timestamp"=> null,"api-key"=>"blah"),                       
                         $urlIn="http://www.example.com/rest")
{
    if(!isset($paramsIn['timestamp']) || is_null($paramsIn['timestamp'])){
        $paramsIn['timestamp'] = time() - 7200;
    }

    // this is now the equivalent of having time() as a default value
}
Sign up to request clarification or add additional context in comments.

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.