Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

class - How to echo a custom object in PHP?

Given a particular class 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
class TheClass {
    public $Name;
    public $Number;
    function MrFunction() { /* bla bla bla */ }

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


echo $theClassInstance;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...