Why can not the variable containing a reference to an object be used in PHP? Why is the output of the object and the reference identical after var_dump ()?


I've a following code snippet written in a file titled "prog_1.php":


  class SimpleClass {
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
      echo $this->var;

  $instance = new SimpleClass();

  $assigned   =  $instance;
  $reference  =& $instance;
  echo "\n";
  echo $reference; //At this step I'm getting a "Catchable fatal error"
  echo "\n";

My first issue is with the below line from above code :

echo $reference;

For this code line I'm getting following error :

**Catchable fatal error:** Object of class SimpleClass could not be converted to string in /var/www/practice/prog_1.php on line 23

I'm not understanding if I could var_dump() the object of a class then why can't I echo the same?

My second doubt is if execute following two statements :


Both the statements given me the same output as follows :

object(SimpleClass)#1 (1) {
  string(15) "a default value"

Why so? Isn't there any difference between object and reference? What does this #1 mean in above output?

Hope someone could clear my above doubts by providing me satisfactory and best in class answers in a simple, easy to understand and crispy language.

Thanks in advance.

To have a string representation of an object, implement the magic __toString() method in the object. This is used to serialize the object for string representation. (You could use this to return (private) members as a string and make your class "echo-able"