Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

489
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda