0

Is it possible to echo class object so it will show some property of this object?

Let's say we've got such class

class Color {

    public $color = "";

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

}

and then we create it's instance and echo it:

$myColor = new Color("red");
echo $myColor; //I want it to echo 'red' ( same as I'd do echo $myColor->color )

What happens here is my object has prop color. And when I have echo $object I want it to really do echo $object->prop

Is it possible to make such 'echoing' handler?

1 Answer 1

3

Implement the magic __toString method:

class Color {

    public $color = "";

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

    public function __toString() {
      return $this->color;
    }

}

This method will be automatically called by PHP if an instance is forced to be converted to a string, e.g. when echoing it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.