2

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

<?php
  ini_set('display_startup_errors',1);
  ini_set('display_errors',1);
  error_reporting(-1);

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

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

  $instance = new SimpleClass();

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

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 :

var_dump($instance);
var_dump($reference);

Both the statements given me the same output as follows :

object(SimpleClass)#1 (1) {
  ["var"]=>
  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.

PHPLover
  • 1
  • 51
  • 158
  • 311
  • 2
    _why can't I echo the same?_ -> see [__toString()](http://php.net/manual/en/language.oop5.magic.php#object.tostring) – Federkun May 23 '15 at 10:12

2 Answers2

1

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"

Armand
  • 215
  • 1
  • 6
  • And to explain your reference question. By reference should be seen as a link using a different variable to the same source variable. "isn't there any difference between object and reference? " A reference is NOT a data type, it's a method of passing a variable by reference instead of making a copy of it. Can besides objects also be used with strings and arrays. – Armand May 23 '15 at 10:51
0

To echo an object or array you have to use print_r($var); the object or array is not a string and echo only outputs strings integers ..etc

Mohamed Belal
  • 610
  • 7
  • 11