无法将类Closure的对象转换为string:filename。

时间:2013-03-12 22:00:45

标签: php

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 个答案:

答案 0 :(得分:8)

几个问题:

  1. 因为你要返回一个闭包,你必须首先将闭包赋值给变量,然后调用函数
  2. 您的$this引用在封闭内不起作用(这就是您use $that代替的原因
  3. 您还需要使用$currencyType在闭包的范围内访问它

  4. 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中的浮点数将为您带来时髦的结果。