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参照はクロージャー内では機能しません (そのため、代わりにuseingを使用しています$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 に答える
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');

ラムダ関数を定義しています。あなたはそれを必要としません。また、これが何らかの精度を持つ場合は、bcmul()を使用する必要があります。PHP のフロートは、ファンキーな結果をもたらします。

于 2013-03-12T22:05:37.483 に答える