A function(actually constructor of another class) needs an object of class temp
as argument. So I define interface itemp
and include itemp $obj
as function argument. This is fine, I must pass class temp
objects to my function. But now I want to set default value to this itemp $obj
argument. How to accomplish this? Or is it not possible?
I will put the test code to clarify:
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
You can't. But you can easily do that:
function func2(itemp $obj = null)
if ($obj === null) {
$obj = new temp('Default');
}
// ....
}