PHP - Object of class could not be converted to string

I'm trying to print a property of the simple class below. But instead i get the error above. I haven't found an answer on similar questions on here. The error triggers on this line:

echo "$object1 name = " . $object1->name . "<br>";

Using XAMPP on Windows Help?

<?php
    $object1 = new User("Pickle", "YouGotIt");  
    print_r($object1);
    $object1->name  = "Alice";

    echo "$object1 name = " . $object1->name . "<br>"; /* this triggers the error */

    class User
    {
        public $name, $password;

        function __construct($n, $p) { // class constructor
            $name = $n;
            $password = $p;
        }
    }
?>

Solution 1:

There are two things wrong in your code,

  • You're using local variables in your class constructor, not instance properties. Your constructor method should be like this:

    function __construct($n, $p) {
        $this->name = $n;
        $this->password = $p;
    }
    
  • Now comes to your error, Object of class could not be converted to string. This is because of this $object in echo statement,

    echo "$object1 name = " ...
          ^^^^^^^^
    

    You need to escape this $object1 with backslash, like this:

    echo "\$object1 name = " . $object1->name . "<br>";