【问题标题】:Using function for default value of parameter in constructor in PHP在PHP的构造函数中使用函数作为参数的默认值
【发布时间】:2014-06-03 15:56:14
【问题描述】:
这里描述了一种解决方法:PHP function as parameter default
但我想知道为什么这不起作用:
class Foo extends Bar {
function __construct($paramsIn=array("timestamp"=>time()-7200,"api-key"=>"blah"),
$urlIn="http://www.example.com/rest")
{ //...etcetc
}
我得到错误:
解析错误:语法错误,filename.php
中出现意外的 '(',期望 ')'
它与 time() 调用特别相关。
【问题讨论】:
标签:
php
oop
constructor
php-5.4
【解决方案1】:
函数参数的默认值仅支持字面量,即字符串、数字、布尔值、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
}