0

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?

2
  • Can you post the code.? Commented Nov 3, 2013 at 13:00
  • Simply write return $calc->do() and in your code echo that desired property or call one of its functions (and that one will echo what you want) Commented Nov 3, 2013 at 13:01

3 Answers 3

3

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';
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Didn't know about this magic method - thanks a lot.
1

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.

1 Comment

I've now implemented this and it works. Thanks a lot!
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.