VG-Electronics
VG-Electronics

Reputation: 279

Casting string number to integer after __toString throws error

I've got a weird problem, I made an equivalent of it which you can see below.
I must have the "__toString" method in the class and I cannot modify the way of reading it (via __toString) cause it's a framework's part.

class Integer{
    private $value = 2;
    
    **Must be implemented:**
    public function __toString(){
        return (string) $this->value;
    }
    
    public function asString(){
        return (string) $this->value;   
    }
}

$test = new Integer;

echo (int) $test->asString(); // 2
**Is used by framework:**
echo (int) $test; // Object of class Integer could not be converted to int

Is it possible to do something with it? Why it behaves like that?
Thanks in advance, I have no clue what to do.

Update: Details

I'm using ValueObject as an ID parameter (how it looks now is presented in the answer for this question). When I do "load" on a fetched row, the Query Builder runs this code (line 1020):

foreach ($values as &$value) {
    $value = (int) $value;
}

And then that error is throwed. I can't change this code. I think I should find a way to change my ValueObject, but I don't know how to do it in Laravel way.

Upvotes: 0

Views: 68

Answers (1)

Rob Ruchte
Rob Ruchte

Reputation: 3707

__toString is only called when you try to represent an object as a string - here you are trying to represent it as an int. You need to cast it to a string first.

echo (int) (string) $test;

Upvotes: 1

Related Questions