sasha199568
sasha199568

Reputation: 1153

Can I embed class objects into strings if class has `__toString` method?

If I have a class which looks something like this

class MyClass {
    private $myvar;

    public function __construct($myvar) {
        $this->myvar = $myvar;
    }

    public function getMyVar() {
        return $this->myvar;
    }

    public function __toString() {
        return "from toString: " . $this->myvar;
    }
}

And then I want to use my class like this

$myclass = new MyClass("myvar value");
echo "Embedded class into a string: $myclass";

From above code I would expect this output

Embedded class into a string: from toString: myvar value

Upvotes: 1

Views: 27

Answers (1)

u_mulder
u_mulder

Reputation: 54831

It is:

public function __toString() {
    return "from toString: " . $this->myvar;
}

Because $myvar in the scope of __toString function is not defined.

A simple fiddle is here https://3v4l.org/YFctl

Upvotes: 1

Related Questions