function convert($currencyType)
{
$that = $this;
return $result = function () use ($that)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
};
}
$currency = new Currency();
echo $currency->convert('EURO');
Run Code Online (Sandbox Code Playgroud)
怎么了?
我收到错误消息:
Catchable fatal error: Object of class Closure could not be converted to string
Run Code Online (Sandbox Code Playgroud)
几个问题:
$this引用将不封闭内工作(这就是为什么你在use荷兰国际集团$that代替)$currencyType在闭包范围内访问它function convert($currencyType)
{
$that =& $this; // Assign by reference here!
return $result = function () use ($that, $currencyType) // Don't forget to actually use $that
{
if (!in_array($currencyType, $that->ratio))
return false;
return ($that->ratio[$currencyType] * $that->money); //a float number
};
}
$currency = new Currency();
$convert = $currency->convert('EURO');
echo $convert(); // You're not actually calling the closure until here!
Run Code Online (Sandbox Code Playgroud)
您必须在括号之间创建函数并在关闭函数时添加括号。
function convert($currencyType)
{
$that = $this;
return $result = (function () use ($that)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
})();
}
$currency = new Currency();
echo $currency->convert('EURO');
Run Code Online (Sandbox Code Playgroud)
只需删除return那里并执行以下操作:
$result = function () use ($that)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
};
return $result();
Run Code Online (Sandbox Code Playgroud)
另外,您是否意识到您没有$that在函数内部使用?
顺便问一下,为什么那里需要一个匿名函数?做就是了:
function convert($currencyType)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
}
Run Code Online (Sandbox Code Playgroud)