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

Lis*_*sky 9 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');
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)

lan*_*ons 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!
Run Code Online (Sandbox Code Playgroud)


cha*_*ser 5

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

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)


Sho*_*hoe 3

只需删除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)