在PHP构造函数中使用函数作为参数的默认值


Using function for default value of parameter in constructor in PHP

这里描述了一种解决方法:PHP函数作为默认参数

但是我想知道为什么这不起作用:

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

我得到错误:

解析错误:语法错误,unexpected '(', expected ')' in filename.php

这是与time()调用相关的

函数参数的默认值只支持字面值,即字符串、数字、布尔值、null和数组。不支持像time()这样的函数调用。这样做的原因是函数签名应该描述接口,并且独立于运行时值。这同样适用于初始化类中的对象属性。

正如你的链接所指出的,解决方法是使用null并在函数体内处理它。

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
}