Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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
like image 256
Lisa Miskovsky Avatar asked Mar 12 '13 22:03

Lisa Miskovsky


3 Answers

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
}
like image 84
Shoe Avatar answered Nov 04 '22 06:11

Shoe


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');
like image 45
chakroun yesser Avatar answered Nov 04 '22 06:11

chakroun yesser


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!
like image 8
landons Avatar answered Nov 04 '22 07:11

landons