Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

486
Views
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;
        }
    }
?>
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
about 4 years ago · Santiago Trujillo Report

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!