PHP函数作为参数默认值


PHP function as parameter default

以以下函数为例:

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()返回的默认值,并且仍然能够用字符串值覆盖它呢?

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

您可以使用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();
    }
}

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

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