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');
怎么了?
我收到错误消息:
Catchable fatal error: Object of class Closure could not be converted to string
答案 0 :(得分:8)
几个问题:
$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!
答案 1 :(得分:3)
您必须在括号之间创建函数并在关闭函数时添加括号。
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');
答案 2 :(得分:1)
只需删除return
并执行:
$result = function () use ($that)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
};
return $result();
另外,您是否意识到您在功能中没有使用$that
?
顺便问一下,为什么你需要匿名功能呢?只是做:
function convert($currencyType)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
}
答案 3 :(得分:0)
class Currency {
function convert($currencyType)
{
if (!in_array($currencyType, $this->ratio))
return false;
return ($this->ratio[$currencyType] * $this->money); //a float number
}
}
$currency = new Currency();
echo $currency->convert('EURO');
您正在定义一个lambda函数。你不需要它。此外,如果要有任何准确性,您应该使用bcmul(); PHP中的浮点数将为您带来时髦的结果。