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');What's wrong?
I'm getting the error message:
Catchable fatal error: Object of class Closure could not be converted to string 7 4 Answers
Couple of issues:
- Because you're returning a closure, you have to first assign the closure to a variable, and then call the function
- Your
$thisreferences won't work inside a closure (which is why you'reuseing$thatinstead) - You need to also use
$currencyTypeto access it in the closure's scope
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 You have to make function between parentheses and add parentheses when closing the function.
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'); Just delete the return there and do:
$result = function () use ($that)
{ if (!in_array($currencyType, $this->ratio)) return false; return ($this->ratio[$currencyType] * $this->money); //a float number
};
return $result();Also, are you realizing you are not using $that inside the function?
By the way, why do you need an anonymous function there? Just do:
function convert($currencyType)
{ if (!in_array($currencyType, $this->ratio)) return false; return ($this->ratio[$currencyType] * $this->money); //a float number
} 5 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');You are defining a lambda function. You don't need it. Also, you should be using bcmul() if this is to have any kind of accuracy; floats in PHP will give you funky results.