Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

490
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda