Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo a custom object in PHP?

Tags:

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.

like image 841
Garet Claborn Avatar asked May 15 '11 23:05

Garet Claborn


People also ask

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

How do you echo a stdClass object?

Show activity on this post. $results = Array ( [0] => stdClass Object ( [title] => Title A [catid] => 1 ) [1] => stdClass Object ( [title] => Title B [catid] => 1 ) ); $str = ""; foreach($arr as $item) { $result . = $item->title .

How do I declare an object in PHP?

To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.


1 Answers

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

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


echo $theClassInstance;
like image 179
prodigitalson Avatar answered Sep 24 '22 00:09

prodigitalson