PHP函数作为参数默认值

5

以以下函数为例:

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()是一个获取函数。

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

如何将其默认值设为$this->_config->db()返回的任何内容,并仍然能够用字符串值覆盖它呢?

3个回答

7

为什么不默认接受NULL值 (使用 is_null() 进行测试),如果是,则调用您的默认函数?


这是我使用的最不显眼的方法,非常感谢。if(is_null($target)) $target = $this->_config->db(); - George Reith

2
您可以使用 is_callable()is_string() 函数来判断。请注意保留 HTML 标签。
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();
    }
}

但是OP想要默认调用特定的方法,而不是接受任意可调用对象? - user268396
1
好的,你可以直接删除 elseif 树的第一部分。这个版本仍然会执行相同的操作,只是增加了传递函数的额外选项。 - DaveRandom

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();
    }
}

我在其他地方都发现“null”作为默认值,而你使用了空字符串。请问为什么?是因为你想让它与自定义值可能的类型(字符串)相同吗?在PHP中有任何原因这样做吗?我只是好奇。 - TheFrost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接