PHP函数作为参数默认值

时间:2012-01-05 10:08:29

标签: php oop function

以下列函数为例:

private function connect($method, $target = $this->_config->db()) {
    try {
        if (!($this->_pointer = @fopen($target, $method)))
            throw new Exception("Unable to connect to database");
    }  catch (Exception $e) {
            echo $e->getMessage();
    }
}

如您所见,我将函数$this->_config->db()插入参数$target,因为它是默认值。我知道这不是正确的语法,而只是试图解释我的目标。

$this->_config->db()是一个getter函数。

现在我知道我可以使用匿名函数并稍后通过$target调用它,但我希望$target也接受直接字符串值。

我怎样才能给它$this->_config->db()返回的默认值,并且仍能用字符串值覆盖它?

3 个答案:

答案 0 :(得分:7)

为什么不默认接​​受NULL值(使用is_null()测试),如果是,请调用默认函数?

答案 1 :(得分:2)

您可以使用is_callable()is_string()

private function connect($method, $target = NULL) {
    if (is_callable($target)) {
        // We were passed a function
        $stringToUse = $target();
    } else if (is_string($target)) {
        // We were passed a string
        $stringToUse = $target;
    } else if ($target === NULL) {
        // We were passed nothing
        $stringToUse = $this->_config->db();
    } else {
        // We were passed something that cannot be used
        echo "Invalid database target argument";
        return;
    }
    try {
        if (!($this->_pointer = @fopen($stringToUse, $method)))
            throw new Exception("Unable to connect to database");
    }  catch (Exception $e) {
            echo $e->getMessage();
    }
}

答案 2 :(得分:1)

我会检查是否传递了值并在方法内部进行简单检查来调用我的函数:

private function connect($method, $target = '') {
    try {
        if ($target === '') {
            $target = $this->_config->db()
        }

        if (!($this->_pointer = @fopen($target, $method))) {
            throw new Exception("Unable to connect to database");
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}