5

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;
        }
    }
?>

2 Answers 2

4

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>";
    
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

$this then (first code) points at a variable $userObj which comes from the parameter. Class properties must be referenced without a $ sign in front of it. Sure this fixed your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.