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
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
}
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');
Couple of issues:
$this
references won't work inside a closure (which is why you're use
ing $that
instead)$currencyType
to access it in the closure's scopefunction 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With