一个函数(实际上是另一个类的构造函数)需要一个对象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