An object of class Closure cannot be converted to a 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 get an error message:

 Catchable fatal error: Object of class Closure could not be converted to string 
+8
php
source share
4 answers

A couple of problems:

  • Since you are returning a closure, you must first assign the closure to the variable and then call the function
  • Your $this links will not work inside closure (so you use ing $that )
  • You need to also use $currencyType to access it in the closing area.

 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! 
+5
source share

You need to make the 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'); 
+2
source share

Just remove return 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, do you realize that you are not using $that inside a function?

By the way, why do I need an anonymous function? Just do:
 function convert($currencyType) { if (!in_array($currencyType, $this->ratio)) return false; return ($this->ratio[$currencyType] * $this->money); //a float number } 
+1
source share
 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 define the lambda function. You do not need it. In addition, you should use bcmul () if this should have any precision; PHP float will give you funky results.

0
source share

All Articles