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;
}
}
?>
There are two things wrong in your code,
You are using local variables in your class constructor, not instance properties. Your constructor method should look like this:
function __construct($n, $p) { $this->name = $n; $this->password = $p; } Now comes your error, the class object could not be converted to a string . This is due to this $object in the echo statement,
echo "$object1";if you want to print the content of your object as a string, you can use
print_r($object, true);In my case the problem was the way I was initializing the class variable.
This was my code:
public function __construct(User $userObj) { $this->$userObj = $userObj; }and I solved it by changing it to the following:
public function __construct(User $userObj) { $this->userObj = $userObj; } The line in the first snippet caused the problem: $this->$userObj = $userObj