26

Given a particular class, TheClass, with an instance foo, is there any way to have PHP echo foo; in a customized manner?

class TheClass {
    public $Name;
    public $Number;
    function MrFunction() { /* bla bla bla */ }
}

$foo = new TheClass();

echo $foo;

As I understand, you cannot overload echo and I realize I could easily have $foo->MrFunction() do the work. However I am wondering if there is a way to code in which

echo $foo prints out $foo->Name and $foo->Number.

We're using PHP Version 5.2.6 but upgrading is not an issue.

3
  • What makes the magic methods 'magic'? Commented May 16, 2011 at 0:09
  • 2
    every time you use them an elephant gets its tusks.... Commented May 16, 2011 at 3:50
  • 2
    @my younger self - they're magic because they are called automatically during execution, without explicitly being called by the developer Commented Jul 13, 2017 at 1:31

4 Answers 4

33

I think you are looking for print_r($foo), or var_dump($foo).

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

Comments

31
class TheClass {
    public $Name;
    public $Number;
    function MrFunction() { /* bla bla bla */ }

   public function __toString()
   {
     return $this->Name . ' '. $this->Number;
   }
}


echo $theClassInstance;

1 Comment

You want need (string) casting as echo explicitly does that for you
9

Yes, using the __toString magic method

Comments

8

What you need is the __toString() magic method. The example in the docs should show what you need.

http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring:

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.