phpobjectdefault-arguments

PHP function to set the default value as an object


A function (actually the constructor of another class) needs an object of class temp as argument. So I define interface itemp and include itemp $obj as the function argument. This is fine, and I must pass class temp objects to my function. But now I want to set default value to this itemp $obj argument. How can I accomplish this?

Or is it not possible?

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

Solution

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

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