Search code examples
phpoopconstructorphp-5.4

Using function for default value of parameter in constructor in PHP


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.


Solution

  • 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
    }