[英]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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.