php函数如何设置默认值为对象?

Sud*_*dhi 16 php object default-arguments

函数(实际上是另一个类的构造函数)需要一个class tempas参数的对象.所以我定义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
Run Code Online (Sandbox Code Playgroud)

Arn*_*anc 27

你不能.但你可以很容易地做到这一点:

function func2(itemp $obj = null)
    if ($obj === null) {
        $obj = new temp('Default');
    }
    // ....
}
Run Code Online (Sandbox Code Playgroud)