PHP函数作为参数默认 [英] PHP function as parameter default

查看:120
本文介绍了PHP函数作为参数默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的函数为例:

pre $ private $ connect $($ method,$ target = $ this-> _config - > db()){
try {
if(!($ this-> _pointer = @fopen($ target,$ method)))
throw new Exception(Unable连接到数据库);
} catch(Exception $ e){
echo $ e-> getMessage();






$你可以看到我插入了函数 $ this-> _config-> db()放入参数 $ target 中,因为它是默认值。



$ this-> _config-> db()我的理解不是正确的语法,只是试图解释我的目标。 是一个getter函数。



现在我知道我可以使用匿名函数并通过 $ target 以后,但是我想 $ target 也接受直接的字符串值。



我怎么能给它一个由 $ this-> _config-> db()返回的默认值并仍然可以用字符串值覆盖它? is_null()测试)如果是这样,请致电您的默认功能?


Take the following function for example:

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

As you can see I inserted the function $this->_config->db() into the parameter $target as it's default value. I understand this is not the correct syntax and am just trying to explain my aim.

$this->_config->db() is a getter function.

Now I know I can use an anonymous function and call it via $target later, but I want $target to also accept direct string values.

How could I give it a default value of the whatever is returned by $this->_config->db() and still be able to overwrite it with a string value?

解决方案

Why not accept NULL values by default (test with is_null()) and if so call your default function?

这篇关于PHP函数作为参数默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆