[英]PHP function as parameter default
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. 如您所见,我将函数
$this->_config->db()
插入到参数$target
作为其默认值。 I understand this is not the correct syntax and am just trying to explain my aim. 我理解这不是正确的语法,只是想解释我的目标。
$this->_config->db()
is a getter function. $this->_config->db()
是一个getter函数。
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. 现在我知道我可以使用匿名函数并稍后通过
$target
调用它,但我希望$target
也接受直接字符串值。
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? 我怎么能给它一个默认值
$this->_config->db()
返回的东西,并且仍能用字符串值覆盖它?
为什么不默认接受NULL值(使用is_null()
测试),如果是,请调用默认函数?
You can use is_callable()
and is_string()
. 您可以使用
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();
}
}
I would perform a check to see if a value was passed and call my function in a simple check inside the method: 我会检查是否传递了一个值,并在方法内部的一个简单检查中调用我的函数:
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.