PHP 函数,用于将默认值设置为对象
2022-08-30 18:25:34
一个函数(实际上是另一个类的构造函数)需要一个对象作为参数。因此,我定义并包含为函数参数。这很好,我必须将对象传递给我的函数。但现在我想将默认值设置为此参数。我该如何做到这一点?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