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.
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!
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 .
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.
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.
class TheClass {
public $Name;
public $Number;
function MrFunction() { /* bla bla bla */ }
public function __toString()
{
return $this->Name . ' '. $this->Number;
}
}
echo $theClassInstance;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With