【发布时间】:2011-10-27 06:09:15
【问题描述】:
一个函数(实际上是另一个类的构造函数)需要一个class temp 的对象作为参数。所以我定义了interface itemp 并包含itemp $obj 作为函数参数。这很好,我必须将class temp 对象传递给我的函数。但现在我想为这个 itemp $obj 参数设置默认值。我怎样才能做到这一点?
还是不可能?
要澄清的测试代码:
interface itemp { public function get(); }
class temp implements itemp
{
private $_var;
public function __construct($var = NULL) { $this->_var = $var; }
public function get() { return $this->_var ; }
}
$defaultTempObj = new temp('Default');
function func1(itemp $obj)
{
print "Got: " . $obj->get() . " as argument.\n";
}
function func2(itemp $obj = $defaultTempObj) //error : unexpected T_VARIABLE
{
print "Got: " . $obj->get() . " as argument.\n";
}
$tempObj = new temp('foo');
func1($defaultTempObj); // Got: Default as argument.
func1($tempObj); // Got : foo as argument.
func1(); // "error : argument 1 must implement interface itemp (should print Default)"
//func2(); // Could not test as I can't define it
【问题讨论】:
-
在这种情况下你可以使用我的小库ValueResolver,请检查我的答案
标签: php object default-arguments