12
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
4

4 回答 4

8

几个问题:

  1. 因为您要返回一个闭包,所以您必须先将闭包分配给一个变量,然后调用该函数
  2. 您的$this引用在闭包内不起作用(这就是您要使用的use原因$that
  3. 您还需要使用$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!
于 2013-03-12T22:09:38.067 回答
4

您必须在括号之间创建函数并在关闭函数时添加括号。

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');
于 2017-04-29T11:14:20.570 回答
2

只需删除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
}
于 2013-03-12T22:05:20.317 回答
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 中的浮点数将为您提供时髦的结果。

于 2013-03-12T22:05:37.483 回答