Object of class Closure could not be converted to string in: filename.

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:

  1. Because you're returning a closure, you have to first assign the closure to a variable, and then call the function
  2. Your $this references won't work inside a closure (which is why you're useing $that instead)
  3. You need to also use $currencyType to 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like