Jason Lipo
Jason Lipo

Reputation: 761

PHP class - return object but echo string

I have a class CalculatePrice. Running this code:

$calc = new CalculatePrice( 10, 20 );
print_r ( $calc->do() );

The do() method returns a different class called PriceObj. If I ran the code echo $calc->do() then I get an error: Object of class PriceObj could not be converted to string.

My question is: how can I still return an object from the do() method but when running an echo to it, it returns a string or even simpler; true or false? Is this possible?

Upvotes: 0

Views: 3119

Answers (3)

Peter van der Wal
Peter van der Wal

Reputation: 11846

That's possible when the object is convertible to a string using the __toString()-method:

class A {
    private $val;

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

    public function __toString() {
       return "I hold ".$this->val;
    }
}

$obj = new A(4);
echo $obj; // will print 'I hold 4';

Upvotes: 3

SamV
SamV

Reputation: 7586

Implement the magic method __toString() on your PriceObj.

So:

public function __toString()
{
    echo $this->result; // The calculated price
}

See http://php.net/manual/en/language.oop5.magic.php

Upvotes: 1

Nanne
Nanne

Reputation: 64419

You can only echo strings. But luckily you can convert your object to a string. This can be done automatically by providing a __toString() function

This is a magic method that does exactly what you want: make a string out of an object. See: http://www.php.net/manual/en/language.oop5.magic.php#object.tostring

The basic thing is you are the only one who knows HOW to make a string from the object (show all or a part of the variables inside for instance), so you need to implement how the string is build yourself.

Upvotes: 1

Related Questions