php function how to set default value as object?

Sudhi picture Sudhi · Aug 15, 2011 · Viewed 14.4k times · Source

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

Answer

Arnaud Le Blanc picture Arnaud Le Blanc · Aug 15, 2011

You can't. But you can easily do that:

function func2(itemp $obj = null)
    if ($obj === null) {
        $obj = new temp('Default');
    }
    // ....
}